2
\$\begingroup\$

Currently trying to migrate two fields of information into one field. We have many, many objects to go through and it takes roughly 12 minutes to loop through all the objects. That would mean the website would be down for 12 minutes and we do not want that. Is there any way to speed up this migration? It works, it's just slow.

from __future__ import unicode_literals
from django.db import migrations, models
def set_people(apps, schema_editor):
 ParticipationCount = apps.get_model('partcount', 'ParticipationCount')
 for row in ParticipationCount.objects.all():
 row.people = row.male + row.female
 row.save()
class Migration(migrations.Migration):
 dependencies = [
 ('partcount', '0002_participationcount_people'),
 ]
 operations = [
 migrations.RunPython(set_people),
 ]

No is an acceptable answer in this case, I am just curious if there is a different way to do this, as loops can be slow. I am using Django 1.8 and python 2.

asked Feb 10, 2020 at 21:31
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Unfortunately you're using django<2.2, since from 2.2 onwards you can use bulk_update , but you can still use something like

ParticipationCount.objects.all().update(
 people=F("male") + F("female")
)

Which will do it in one query to save time. This will fail for certain fields in Postgres however as it requires some specific type casting, but this can be done within the query

answered Feb 11, 2020 at 14:38
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Works swimmingly! Thank you so much! Just had to import F from django.db.models to get it to work \$\endgroup\$ Commented Feb 26, 2020 at 13:41

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.