Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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])
like image 997
Piva Avatar asked May 07 '26 22:05

Piva


1 Answers

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).

like image 167
Daniel Roseman Avatar answered May 10 '26 12:05

Daniel Roseman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!