django create or update code example

Example 1: update django

python -m pip install -U Django

Example 2: bulk create django

bulk_create(objs, batch_size = None, ignore_conflicts = False)

#eg
Entry.objects.bulk_create([
...     Entry(headline='This is a test'),
...     Entry(headline='This is only a test'),
... ])
# inserts in one query (usually), caveats below:
# doesn't signal pre_save and post_save 
# cant use child models
# no many-to-many
# obj list fully evaluates if objs is a generator

Example 3: django get or create object

try:
    obj = Person.objects.get(first_name='John', last_name='Lennon')
except Person.DoesNotExist:
    obj = Person(first_name='John', last_name='Lennon', birthday=date(1940, 10, 9))
    obj.save()

Here, with concurrent requests, multiple attempts to save a Person with the same parameters may be made. To avoid this race condition, the above example can be rewritten using get_or_create() like so:

obj, created = Person.objects.get_or_create(
    first_name='John',
    last_name='Lennon',
    defaults={'birthday': date(1940, 10, 9)},
)
Any keyword arguments passed to get_or_create()except an optional one called defaults — will be used in a get() call. If an object is found, get_or_create() returns a tuple of that object and False.