英文:
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("user"))
total = request.data.get("carttotal")
usercart = Cart.objects.update_or_create(user=user, cart_total=total)
products = request.data.getlist("products")
for product in products:
obj = json.loads(product)
id = obj.get("id")
qty = obj.get("qty")
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("Items added or updated", 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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论