开发者

How to save a ForeignKey without retrieving the foreign object instance?

I have a model in which I want to save a new instance (row). I have the primary key for the ForeignKey but I do not have the object itself (suppose it came from somewhere). Is there any way to save it without raw SQL and without having to get the instance?

Here is the model:

class UserLocale(models.Model):

    user = models.ForeignKey(KingUser)
    locale = models.ForeignKey(Locale)

Now suppose I have the locale primary key ('en_US') but I do not have the object itself. What I'm doing to save it is this:

def save_locale(user_instance, locale_name):
    locale = Locale.objects.get(pk=locale_name)
    UserLocale.objects.create(user=user_instance, locale=locale)

I know I can do it in one step with raw SQL, but I was wondering if I can do it in Django query model.

edit:

Yes, UserLocale is a M2M middle table. I know it would have been nicer to make a ManyToMany field, but it is legacy code.

Here is my SQL attempt (no tests, I'm writting by hand as I'm away from the code):

def save_raw_sql(user_instance, locale_name):

    query = """
            INSERT开发者_开发问答 INTO 
                project_userlocale (user_id, locale_id)
            values (%s, %s)
            """

     UserLocale.objects.raw(query, [user_instance.id, locale_name])


You can just use the id field underlying the ForeignKey object:

UserLocale.objects.create(user=user_instance, locale_id=locale)

(I presume the reference to Locale in your last line should actually have been UserLocale).


def save_locale(user_instance, locale_name):
    user_locale = UserLocale()
    user_locale.user = user_instance
    user_locale.locale_id = locale_name
    user_locale.save()

if u invoke the object, you have the .locale atribute that is a reference to the class Locale, and .locale_id that contain the real value for the field.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜