[Django]-Django get() returned more than one

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.

👤Ykh

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.

👤shaded

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.

Leave a comment