我正在使用网上商店应用。我需要从m2m字段中获取单个项目,以便可以对其进行迭代并获得单个attirbutes(例如图像等)。感谢您的帮助
class Item(models.Model):
title = models.CharField(max_length=100)
price = models.FloatField()
image = models.ImageField(default='default.jpg', upload_to='product_pics')
class OrderItem(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE, blank=True, null=True)
item = models.ForeignKey(Item, on_delete=models.CASCADE,
related_name="order_item")
quantity = models.IntegerField(default=1)
ordered = models.BooleanField(default=False)
class Order(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
items = models.ManyToManyField(OrderItem, related_name="orders")
start_date = models.DateTimeField(auto_now_add=True)
ordered = models.BooleanField(default=False)
#VIEWS
def cart_items(request):
all_items = Item.objects.filter(order_item__orders_user=request.user)
if all_items.exists():
context = {
"items":all_items
}
return render(request, "shop/cart.html", context)
return redirect("profile")
#template loop
for item in items:
item.image
答案 0 :(得分:0)
您需要更改Alt+Shift+L
字段以将items
用作穿透表docs
OrderItem
然后您可以为这样的用户获取最新订单的所有商品
items = models.ManyToManyField(Item, through=OrderItem, related_name="orders")