Django get()返回了多个

2022-02-27 00:00:00 python django many-to-many

问题描述

我有此错误,如何修复此错误?

get()返回多个事件--它返回%2!

你们能帮助我理解这是什么意思吗?或许可以提前告诉我以后如何避免此错误?

模型

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)

视图

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

解决方案

from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
try:
    instance = Instance.objects.get(name=name)
except (ObjectDoesNotExist, MultipleObjectsReturned):
    pass

get()引发MultipleObjectsReturned如果找到多个对象,则更多信息here。 错误由event_detail = Event.objects.get(pk=pk)引起,请检查您的事件主键是否唯一。

相关文章