Let's say I have a list of dicts with emails and birthdays:
p = [\ {'email': 'someone@somewhere.com', 'birthday': '1990-01-01'}, {'email': 'someone_else@somewhereelse.com', 'birthday': '1980-02-05'}, #...etc ]
I want to update the
People
objects in the database. The raw sql would normally have as many queries aslen(p)
, so this makes me think of doing:from django.db import IntegrityError, transaction for person in p: try: with transaction.atomic(): People.objects.filter(email=person['email']).update(birthday=person['birthday']) except IntegrityError: #handle the exception
I'm not experienced enough in Django to know if this is good practice though. What's the most pythonic way to express what I'm trying to do?
score:3
When you filter and update, the same update will be applied to all the filtered entries. Django doesn't provide a bulk update operation where you can update different values on different entries.
You can make your code better by including the for
loop inside the transaction.atomic()
block instead of having the atomic block for each entry in the for loop:
with transaction.atomic():
for person in p:
try:
People.objects.filter(email=person['email']).update(birthday=person['birthday'])
except IntegrityError:
#handle the exception
score:3
There is a library: django-bulk-update.
people = Person.objects.all()
for person in people:
person.name = random.choice(random_names)
bulk_update(people, update_fields=['name'])
# or
Person.objects.bulk_update(people, update_fields=['name'])
score:5
Using Django's bulk_update
- https://docs.djangoproject.com/en/3.1/ref/models/querysets/#bulk-update
objs = []
for person in p:
obj = People.objects.get(email=person['email'])
obj.birthday = person['birthday']
objs.append(obj)
People.objects.bulk_update(objs, ['birthday'], batch_size=1000)
Credit To: stackoverflow.com
Related Query
- Best way to bulk update query with dynamic values conditionally in Django
- Way to bulk update (with unique values) in Django
- Efficient way to bulk insert with get_or_create() in Django (SQL, Python, Django)
- Django bulk update with string replace
- MySQL INSERT ... ON DUPLICATE KEY UPDATE with django 1.4 for bulk insert
- Django model update or create object with unique constraint
- Bulk update with JSONField in Django
- Django List Serializer bulk update failing with 'QuerySet' object has no attribute 'pk'
- Django bulk update with data two tables over
- Bulk update in django with calculations
- How to update a list of objects in Django with a unique constraint?
- How to update Django model data with a unique constraint using a ModelForm?
- Django 2.1+ bulk update records with the count of their related records?
- Storing unique values in django hstorefield with postgresql
- Efficient method to update one field with different values in a django model
- Better way of sending bulk requests to a remote API with Django Celery?
- Django update model with unique field
- Django select only rows with duplicate field values
- Distributing Django projects with unique SECRET_KEYs
- django most efficient way to count same field values in a query
- Django update queryset with annotation
- The way to use background-image in css files with Django
- Efficient way to update multiple fields of Django model object
- django - update model with FormView and ModelForm
- Update new Django and Python 2.7.* with virtualenv on Dreamhost (with passenger)
- The best/recommended way to translate Django database values
- Unique foreign key pairs with Django
- Is there a way to auto-increment a Django field with respect to a foreign key?
- Django Rest Framework model serializer with out unique together validation
- What is the right way to use angular2 http requests with Django CSRF protection?
More Query from same tag
- Annotate a QuerySet with the latest value from a filtered join
- Django RSS feed according to category
- How to save multiple objects at once to Django database
- Django view returning count of users based on last_login
- Django foo_display with values()
- How to get a certain number of elements in django template
- Django accessing formset data
- Reformat Django REST Framework Serializer to get Output
- Getting field value with DjangoRestFramework serializer
- ImportError: libpq.so.5: cannot open shared object file: No such file or directory
- Celery with Supervisord workers are not working Isolated
- DJango: Multiple instances of an application in a single project
- Django - prevent duplicate POST requests when user clicking submit button multiple times?
- Template not found with Django on Heroku
- Django code organization