[Django]-Does django cache model data between queries?

3πŸ‘

βœ…

It seems like you are encountering a race condition here. If you take a look at the code for get_or_create that Django provides for you natively it looks similar to yours

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()

In fact the code above may also be subject to race condition and create more objects than one which the documentation also says: However, if uniqueness is not enforced at the database level for the kwargs used in a get_or_create call (see unique or unique_together), this method is prone to a race-condition which can result in multiple rows with the same parameters being inserted simultaneously.

So the solution for you is make field unique in this case.

Or if the field can’t be unique I would suggest that you try out using transactions explicitly.

from django.db import transaction 

with transaction.atomic():
    # do_database_stuff
πŸ‘€Jonathan

1πŸ‘

make field unique

#your model
class MyModel(models.Model):
      field = modesl.IntegerField(unique=True)

      def __unicode__(self):
          return '%s' % self.field


"""your code to interac with the model (Don't matther where you have this code 
(in the view, or elsewhere)), the behavior of the code is going to be the same. 
views.py just is a python file."""

from you_app.models import MyModel
from django.db import IntegrityError

def insert_item(list_item):
    for item in list_item:
        try:
            itemobj = MyModel.objects.create(field=item)
        except IntegrityError:
            #exists, posible you want to make some update here
            itemobj = MyModel.objects.get(field=item)
            #maybe update...
        else:
            #do whatevert you want with itemobj
            print itemobj
πŸ‘€Pjl

Leave a comment