3

I have this error, how can I fix this?

get() returned more than one Event -- it returned 2!

Can you guys help me understand what that means and maybe tell me in advance how to avoid this error in future?

MODEL

class Event (models.Model):
    name = models.CharField(max_length=100)
    date = models.DateField(default='')
    dicript = models.CharField(max_length=50, default='Описание отсутствует')
    category = models.ForeignKey(Category,on_delete=models.CASCADE)
    adress = models.TextField(max_length=300)
    user = models.ForeignKey(User,related_name="creator",null=True)
    subs = models.ManyToManyField(User, related_name='subs',blank=True)

    @classmethod
    def make_sub(cls, this_user, sub_event):
        event, created = cls.objects.get_or_create(
            user=this_user
        )
        sub_event.subs.add(this_user)

VIEWS

def cards_detail (request,pk=None):
    # if pk:
    event_detail = Event.objects.get(pk=pk)
    subs = event_detail.subs.count()

    # else:
    #     return CardsView()
    args = {'event_detail':event_detail,'subs':subs}
    return render(request,'events/cards_detail.html',args)


class CardsView (TemplateView):`
    template_name = 'events/cards.html'

    def get (self,request):
        events = Event.objects.all()
        return render(request,self.template_name,{'events':events })

def subs_to_event (request,pk=None):

    event = Event.objects.filter(pk=pk)
    Event.make_sub(request.user,event)


    return redirect('events:cards')
Sardorbek Imomaliev
  • 14,861
  • 2
  • 51
  • 63
rumor
  • 31
  • 1
  • 1
  • 2

3 Answers3

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
  • 7,567
  • 1
  • 22
  • 31
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
  • 89
  • 1
  • 6
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.

  • This shouldn't be a case, since he queried for primary key – Ersain Jan 25 '22 at 10:26
  • This does not really answer the question. If you have a different question, you can ask it by clicking [Ask Question](https://stackoverflow.com/questions/ask). To get notified when this question gets new answers, you can [follow this question](https://meta.stackexchange.com/q/345661). Once you have enough [reputation](https://stackoverflow.com/help/whats-reputation), you can also [add a bounty](https://stackoverflow.com/help/privileges/set-bounties) to draw more attention to this question. - [From Review](/review/late-answers/30901010) – creimers Jan 31 '22 at 08:14