django - get() returned more than one topic

前端 未结 6 2217
不知归路
不知归路 2020-11-30 02:30

When I tried to relate an attribute with another one which has an M to M relation I received this error:

get() returned more than one

6条回答
  •  囚心锁ツ
    2020-11-30 02:38

    To add to CrazyGeek's answer, get or get_or_create queries work only when there's one instance of the object in the database, filter is for two or more.

    If a query can be for single or multiple instances, it's best to add an ID to the div and use an if statement e.g.

    def updateUserCollection(request):
        data = json.loads(request.body)
        card_id = data['card_id']
        action = data['action']
    
        user = request.user
        card = Cards.objects.get(card_id=card_id)
    
        if data-action == 'add':
            collection = Collection.objects.get_or_create(user=user, card=card)
            collection.quantity + 1
            collection.save()
    
        elif data-action == 'remove':
            collection = Cards.objects.filter(user=user, card=card)
            collection.quantity = 0
            collection.update()
    

    Note: .save() becomes .update() for updating multiple objects. Hope this helps someone, gave me a long day's headache.

提交回复
热议问题