Updating the database using Shell in Django

Recently, I had a urgent need to change or say, update the database fields without affecting any code of my Django projects. This came to me as a challenge. Sometimes these challenges help us to learn a lot.

I had a table named ‘Amount’ which had 2 columns as field and other_field.These columns were filled in such a way that either other_field was null or other_field = field. I wanted 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 were equal, there field should be assigned a string  “OTHER” and other_field should remain as
such.

The solution to this is :

Go to Django shell in your project, by applying

python manage.py shell

This will take you an interactive python like shell with prompt as like

Python 2.7.3 (default, Apr 20 2012, 22:44:07)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>

Then type the following code in the shell prompt :

from TCC.automation.models import *
from django.db.models import F                                          
Amount.objects.filter(field = F("other_field")).update(field="OTHER")

This update all the entries in field whose values where equal to other_field to value “OTHER”

Django provides F() expressions for performing this kind of relative update.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s