Home > Mobile >  Update Django model object field from shell
Update Django model object field from shell

Time:12-30

Model field displaying some zip codes as 4 characters only, ex: 1234

I want to change all zip codes with 4 characters to 5 by adding a "0" at the start, ex: 01234

Trying to find a way to do this from shell because I have a few thousand objects

from app.models import Entry

I tried:

Entry.objects.filter(len(zip_code)==4).update("0" zip_code)

and

Entry.objects.filter(len(zip_code)==4).update(f("0" {zip_code}))

Error returned:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
NameError: name 'zip_code' is not defined

CodePudding user response:

You could make a migration for that:

first, create an empty migration:

python manage.py makemigrations your_app_name --empty

in that newly created migration, define your function:

def update_zipcodes(apps, schema):
    YourModel = apps.get_model("your_app_name", "YourModel")  # django will retrieve your model here
    
    for obj in YourModel.objects.all():
        if len(obj.zip_code) == 4:
            old_zip_code = obj.zip_code
            obj.zip_code = f'0{old_zip_code}'
            obj.save()

Then call that function in the list operations (at the bottom of the file). your list should look like this

operations = [
    # migrations.RunPython.noop can be replaced here with a reverse function
    # (in case you want to "un-apply" that migration later for some reason)
    migrations.RunPython(update_zipcodes, migrations.RunPython.noop),
]

finally, you apply your migration by calling :

python manage.py migrate
  • Related