首页 > 解决方案 > 尝试获取电子商务 Django 项目中每个项目的总销售额

问题描述

我试图得到总数。付款后的已售商品。

当订单支付ordered = models.BooleanField(default=False)成为True

我尝试将上下文与总销售额添加,但它不起作用,所以我将它保留在下面的代码中,但对其进行了评论。

我也尝试添加一个具有总计数的函数,但我不断得到'Item' object has no attribute 'order_set'我将其保留在下面以供参考

这是项目models.py

class Item(models.Model):
    title = models.CharField(max_length=100)

    def __str__(self):
        return self.title
    
    # def count_sold(self):
      #  return self.order_set.filter(ordered=True).count()

这是 OrderItemmodels.py

class OrderItem(models.Model):
    ordered = models.BooleanField(default=False)
    item = models.ForeignKey(Item, on_delete=models.CASCADE)

这是订单

class Order(models.Model):
    items = models.ManyToManyField(OrderItem)
    ordered = models.BooleanField(default=False)

这是views.py

class DesignerOnlyPostListView(ListView):
    model = Item
    template_name = "designer_only_posts.html"
    context_object_name = 'items'
    paginate_by = 6

    def get_queryset(self):
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        return Item.objects.filter(designer=user).order_by('-timestamp')

    def get_context_data(self, **kwargs):
        comments = Comment.objects.all()
        # total_sold = Order.objects.all()
        context = super().get_context_data(**kwargs)
        context["total_comments"] = comments.count()
        # context["total_sold"] = total_sold.count()
        return context

这是模板

{% for item in items %}
<tr>
    <td>No. of Sold:</td>
    <td>{{ item.total_sold.all.count }}</td>
</tr>
{% endfor %}

这是我尝试使用 count_sold 函数时的模板

                                    <tr>-->
<!--                                        <td>No. of Reviews:</td>-->
<!--                                        <td>{{ item.count_sold  }}</td>-->
<!--                                    </tr>

标签: pythondjangodjango-views

解决方案


Item 没有 order_set,因为这两个模型之间没有关系。

  • 项目与 OrderItem 相关
  • OrderItem 与 Order 有关

也许您可以尝试以下方法:

class Item(models.Model):
    title = models.CharField(max_length=100)
    
    def __str__(self):
        return self.title
    
    @property
    def count_sold(self):
        return self.orderitem_set.filter(ordered=True).count()

和模板

{% for item in items %}
    <tr>
        <td>No. of Sold:</td>
        <td>{{ item.count_sold }}</td>
    </tr>
{% endfor %}

推荐阅读