Reputation: 35
How to implement sql statement
update table1
set field1 = field2
using Django ORM.
Upvotes: 1
Views: 1930
Reputation: 47374
You can use update()
with F expression
:
from django.db.models import F
Table1.objects.update(field1=F('field2'))
Upvotes: 3
Reputation: 477684
Given you have a mode Table1
with the two fields, you can do this with:
Table1.objects.update(field1=F('field2'))
We here use a F-expression
such that we reference to the field, not the value 'field2'
. The statement with F(..)
would result in setting all columns to the string 'field2'
(given of course that is even possible, since field1
has to be able to store text data).
With Table1.objects
we obtain access to the queryset of Table1
with (if not further specified) all objects. Note that we do not load these in memory. It is used to construct a query.
With .update(..)
we can then update data in the rows that correspond to the queryset (here all rows, but we could have filtered as well).
Like said before, we can not simply pass 'field2'
as a value. Since the ORM interprets this to setting field1
of all rows to the string 'field2'
. We use an F
-expression to reference to the column.
Upvotes: 2