user3749797 user3749797 - 7 months ago 39
Python Question

Django bulk update with history deletion

I'm trying to optimize my Django backend performance. I have a model User that I track with Django Simple History (https://django-simple-history.readthedocs.io/en/latest/).

I want to be able to bulk update my User model and then remove this from history. For an individual User, this would look like this:

u = User.objects.get(id=user_id)
u.name = "new name"
u.save()
u.history.first().delete() # I don't want to track this change.


Performance-wise, which is better?

Option 1:

users = User.objects.filter(needs_updating=True)
for user in users:
user.name = "New name"
user.save()
user.history.first().delete()


Option 2:

User.objects.filter(needs_updating=True).update(name="new name")
User.history.filter(name="new name").delete()

2ps 2ps
Answer

Option #2 for all n where n = the number of users that need updating and assuming that the needs_updating and name fields are flagged with db_index or are otherwise indexed in the database (assuming that you have tested it and it works).

By my count: Option #1 will do 1 + 2*n queries against the database while while Option #2 always does 2 queries against the database.