【问题标题】:How To Save A Model Instance that I Just Created In Django views?如何保存我刚刚在 Django 视图中创建的模型实例?
【发布时间】:2020-04-17 14:36:00
【问题描述】:

在我的 views.py 中,这应该保存一个购物车项目:

cart = Cart.objects.get_or_create(owner=owner, is_ordered=False, ref_code=ref_code)

        insert = OrderItem(item_count=item_count, price=total_price, color=color, size=size, product=product,
                        cart=cart)

        insert.save()

但是,即使创建了购物车,它也会给我这个错误:

无法分配“(, False)”:“OrderItem.cart”必须是“Cart”实例。

【问题讨论】:

  • 错误```无法分配“(,False)”:“OrderItem.cart”必须是“Cart”实例。 ```

标签: django postgresql django-models django-templates django-views


【解决方案1】:

get_or_create 的结果是一个元组 (object, bool)。因此,当您执行cart=cart 时,实际上是将元组(, False) 分配给cart(这就是错误所说的)。

只需将您的第一行更正如下:

cart, created = Cart.objects.get_or_create(owner=owner, is_ordered=False, ref_code=ref_code)

【讨论】:

    【解决方案2】:
    cart, cart_response = Cart.objects.get_or_create(owner=owner, is_ordered=False, ref_code=ref_code)
    OrderItem.create(cart=cart, item_count=item_count, price=total_price, color=color, size=size, product=product)
    

    使用 create 你可以跳过 .save()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-04
      • 1970-01-01
      • 1970-01-01
      • 2011-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多