Set a django object property through a subquery

Viewed 175

I have an object of type Foo with a ForeignKey to a Bar. Bar has a property called slug.

I can do

myfoo.bar = Bar.objects.get(slug='123')

But this would add an extra query. Is it possible to have Django generate the assignment as a sub-query within the update?

i.e. generate SQL similar to:

UPDATE myfoo SET bar_id = (select id from bar where slug = '123')
1 Answers

You can use a Django Subquery expression:

from django.db.models import Subquery

# create the "SELECT id FROM bar WHERE slug = '123' LIMIT 1" subquery
subquery = Bar.objects.filter(slug='123')[:1]
# update only the correct foo object with this subquery
Foo.objects.filter(pk=myfoo.pk).update(bar=Subquery(subquery))
# refresh the variable so that `myfoo.bar` is correct
myfoo.refresh_from_db()
Related