Django get()返回了多个

时间:2017-06-18 22:39:24

标签: python django many-to-many

我有这个错误,我该如何解决?

  

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

你能帮我理解这意味着什么,也许可以提前告诉我如何避免这个错误?

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)

视图

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

2 个答案:

答案 0 :(得分:4)

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)引起的,请检查您的活动pk是否唯一。

答案 1 :(得分:1)

基本上,cls对象在' get_or_create()'的get部分获得了多个值。 get()只返回一个对象,而filter返回一个dict(ish)。 把它放在试一试/除外。所以你有:

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

这样,如果找到多个对象,它将处理异常并将查询更改为过滤器以接收多个对象查询集。如果没有找到记录,则无需捕获Object.DoesNotExist,因为创建部件会创建新对象。