django “Order”对象没有属性“orderitem_set”

velaa5lx  于 2023-04-13  发布在  Go
关注(0)|答案(1)|浏览(119)

我正在尝试获取每个订单的订单项。我是这样尝试的:

models.py

class Order(models.Model):
    customer= models.ForeignKey(Users,on_delete=models.SET_NULL,null=True, blank=False)
    date_oder= models.DateTimeField(auto_now_add=True)
    status= models.BooleanField(default=False)
    transaction_id= models.CharField(max_length=100, null=True)
    delivery_date= models.DateTimeField(auto_now_add=True)
    delivered= models.DateTimeField(auto_now=True)
    def __str__(self) :
        return str(self.id)
    @property
    def get_cart_total(self):
        orderitems = self.orderitem_set.all()
        total = sum([item.get_total for item in orderitems])
        return total
    @property
    def get_cart_items(self):
        orderitems = self.orderitem_set.all()
        total = sum([item.quantity for item in orderitems])
        return total 
    
    
class Order_detail(models.Model):
    product= models.ForeignKey(Products,on_delete=models.SET_NULL,null=True, blank=False)
    order= models.ForeignKey(Order,on_delete=models.SET_NULL,null=True, blank=False, related_name='order_items')
    quantity=models.IntegerField(default=0,null=True, blank=True)
    date_added=models.DateTimeField(auto_now_add=True)
    def get_total(self):
        total= self.product.pro_price * self.quantity
        return total

查看.py

def cart(request):
    if request.user.is_authenticated:
        customer = request.user.customer
        order, created = Order.objects.get_or_create(customer = customer ,status = False)
        items = order.orderitem_set.all()
    else:   
        items = []
        order = {'get_cart_total':0,'get_cart_items':0}
        
    context = {'items':items , 'order': order}
    return render(request,'app/cart.html',context)

但我得到以下错误:
/cart/ 'Order'对象没有属性'orderitem_set'时出错
我该如何解决这个问题?

8iwquhpp

8iwquhpp1#

如果要访问Order_detail模型的值,可以使用为Order模型指定的相关名称order_items。此相关名称允许您访问特定Order对象的相关Order_detail对象。
例如,如果您有一个名为my_order的Order对象,则可以使用my_order.order_items.all()访问相关的Order_detail对象。这将返回与my_order对象相关的所有Order_detail对象的QuerySet。
如果你愿意,你也可以使用orderdetail_set

相关问题