字段 id 预期应为数字,但得到的是 <Cart: John's cart>

huangapple go评论62阅读模式
英文:

Field id expected a number but got <Cart: John's cart>

问题

Django 对这行代码报错:

exists = Entry.objects.all().filter(cart=usercart, product=product)


Django 报错说:字段 id 期望是一个数字,但得到了 <Cart: John's cart>。为什么会提到 id 字段,尽管我明确指定了 cart 来过滤,因为我没有 Entry 的 id。
英文:

I have this view I would like to create a cart or update the entries if the cart is already created and if a product is already in the cart then just update its quantity. I am getting an error saying Field id expected a number but got <Cart: John's cart>. Why is the id field even mentioned when I specifically put cart to filter, because I do not have the id of the Entry

class CreateCart(generics.CreateAPIView):
    permission_classes = [permissions.IsAuthenticated]
    serializer_class = CartSerializer   
    def post(self, request):
        user = User.objects.get(id=request.data.get(&quot;user&quot;))
        total = request.data.get(&quot;carttotal&quot;)
        usercart = Cart.objects.update_or_create(user=user, cart_total=total)
        products = request.data.getlist(&quot;products&quot;)
        for product in products:
            obj = json.loads(product)
            id = obj.get(&quot;id&quot;)
            qty = obj.get(&quot;qty&quot;)
            product = Product.objects.get(id=id)
            exists = Entry.objects.all().filter(cart=usercart, product=product)
            if exists:
                exists.quantity = qty
            else:
                Entry.objects.create(product=product, cart=usercart, quantity=qty)
        return Response(&quot;Items added or updated&quot;, status=HTTP_201_CREATED)

This line Django is complaining about:

exists = Entry.objects.all().filter(cart=usercart, product=product)

答案1

得分: 1

update_or_create()方法首先返回一个包含对象和一个布尔值的元组,指示它是创建还是更新。因此,你应该解包这个元组以获取实际的Cart实例,如下所示:

usercart, created = Cart.objects.update_or_create(user=user, cart_total=total)
英文:

At first, the update_or_create() method returns a tuple containing the object and a boolean value indicating whether it was created or updated. So, you should unpack the tuple to get the actual Cart instance as:

usercart, created = Cart.objects.update_or_create(user=user, cart_total=total)

huangapple
  • 本文由 发表于 2023年3月3日 23:35:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75629063.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定