suppose I have two models:
class ModelA(models.Model):
...
field = models.TextField(max_length=200)
class ModelB(models.Model):
...
field = models.TextField(max_length=200)
And I want to copy the values from ModelA
to ModelB
without raw SQL, In Django’s ORM
I’ve tried many variations and I came up with this:
from django.db.models import F, Subquery, OuterRef
a_objs = ModelA.objects.filter(pk=OuterRef('pk')).values('pk')
ModelB.objects.filter(pk=Subquery(a_objs)).update(field=F(OuterRef('field')))
This code fails in the update clause, how can I reference the another model field?
that generates the following query:
UPDATE model_b
SET model_b.field = model_a.field
FROM model_a
WHERE model_a.id = model_b.id
New contributor
ormsh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.