I've been having a rought time saving data to a MySQL database.
This is on a Django 1.4.22 legacy project running several celery-driven tasks to generate reports.
At first I used the get_or_create method but soon it was clear that it wasn't operating correctly as they were a lot of Duplicate Entry errors. So I relied to stuff like the following, making a queryset, then checking it with the exists() method, then creating it if necessary or updating it:
There's only one instance to be found each time (that's why I want to make a update or create action)
qs_snapshot = StatsSnapshot.objects.filter(list=list_id,
created_at__gte=today,
created_at__lt=end_day)
if qs_snapshot.exists():
snapshot = qs_snapshot.get()
qs_snapshot.update(**dict_stats)
else:
try:
snapshot = StatsSnapshot.objects.create(**dict_stats)
except IntegrityError:
# Duplicate entry error, upgrade the data instead or recreating it
# There's no atomicity guaranted so sometimes there's really an
# instance saved after the exists() and before the create()
snapshot = qs_snapshot.get()
qs_snapshot.update(**dict_stats)
So I've got this ugly try, but still it doesn't do what i'm specting as on the exception body, the snapshot = qs_snapshot.get() now raises a DoesNotExist: StatsSnapshot matching query does not exist. How's this even possible? I'm double checking!
I've tried several tips given here, including the fix for the mysql sequences but nothing seems to fix it. Also it does happen with different reports (lists) each time