8👍
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
try:
instance = Instance.objects.get(name=name)
except (ObjectDoesNotExist, MultipleObjectsReturned):
pass
get() raises MultipleObjectsReturned
if more than one object was found,more info here.
the error is cause by event_detail = Event.objects.get(pk=pk)
, check your event pk is unique.
2👍
Basically, the cls object is getting more than one value on the get part of the ‘get_or_create()’. get() returns only a single object whereas filter returns a dict(ish).
Put it in a try/except instead. So you’ll have:
try:
event, created = cls.objects.get_or_create(
user=this_user
)
except cls.MultipleObjectsReturned:
event = cls.objects.filter(user=this_user).order_by('id').first()
This way if multiple objects are found, it handles the exception and changes the query to a filter to receive the multiple object queryset. No need to catch the Object.DoesNotExist as the create part creates a new object if no record is found.
- [Django]-How does djangoproject.com do its deploy to prod? Should I package my django project to deploy it?
- [Django]-How to throw custom exception with custom error code on fly in django rest framework and override default fields in exception response
- [Django]-Django creates the test database for Postgresql with incorrect sequences start values
- [Django]-ModuleNotFoundError : no module named : crispy_forms
- [Django]-Use django-import-export with class based views
0👍
I also face the same error:
get() returned more than one — it returned 4!
The error was that I forgot to make a migration for the newly added fields in the model.
- [Django]-Django admin shows models name with extra "s" at the end
- [Django]-Django Foreign Keys Breaking with Multi-Table Inheritance
- [Django]-Django on Aptana Studio 3.0
- [Django]-How should I upgrade from bradjasper's django-jsonfield to Django's built-in jsonfield?
- [Django]-Use Django-Storages with IAM Instance Profiles