Database Query in Shell

8 views
Skip to first unread message

Sandeep kaur

unread,
May 27, 2012, 7:28:06 AM5/27/12
to django-users
I have a table Amounts which has 2 columns field and other_field.
These columns are filled in such a way that either other_field is null
or other_field = field.
I want to make a database query such that

if field == other_field :
field = "OTHER"
else:
field = field

That means the entries in table where 2 columns are equal, there field
should be assigned a string "OTHER" and other_field should remain as
such.
How can I give such query in shell.

--
Sandeep Kaur
E-Mail: mkaur...@gmail.com
Blog: sandymadaan.wordpress.com

mgc_djan...@chamberlain.net.au

unread,
May 27, 2012, 8:35:19 AM5/27/12
to django...@googlegroups.com, Sandeep kaur
On 27/05/2012 9:28 PM, Sandeep kaur wrote:
> I have a table Amounts which has 2 columns field and other_field.
> These columns are filled in such a way that either other_field is null
> or other_field = field.
> I want to make a database query such that
>
> if field == other_field :
> field = "OTHER"
> else:
> field = field
>
> That means the entries in table where 2 columns are equal, there field
> should be assigned a string "OTHER" and other_field should remain as
> such.
> How can I give such query in shell.
>
To get a queryset containing all the objects where field == other_field
should be something like the following:

from django.db.models import F

Amounts.objects.filter(field = F("other_field"))

to then update all those objects with "OTHER" as the value for field
would be:

Amounts.objects.filter(field = F("other_field")).update(field="OTHER")

Note that this won't execute the "else" portion above, but as it is not
making any change (field already equals field), I assume this isn't an
issue.

Regards,
Michael.

Sandeep kaur

unread,
May 27, 2012, 9:16:13 AM5/27/12
to mgc_djan...@chamberlain.net.au, django...@googlegroups.com
On Sun, May 27, 2012 at 6:05 PM, <mgc_djan...@chamberlain.net.au> wrote:

> To get a queryset containing all the objects where field == other_field
> should be something like the following:
>
> from django.db.models import F
>
> Amounts.objects.filter(field = F("other_field"))
>
> to then update all those objects with "OTHER" as the value for field would
> be:
>
> Amounts.objects.filter(field = F("other_field")).update(field="OTHER")
>
> Note that this won't execute the "else" portion above, but as it is not
> making any change (field already equals field), I assume this isn't an
> issue.
>
You are great, sir.
Thank you.
The query successfully updated the field column as was required.
Reply all
Reply to author
Forward
0 new messages