A_K
A_K

Reputation: 912

Trying to get Total Sold for each Item in E-commerce Django Project

I am trying to get the total no. of a sold item after payment is made.

When the order is paid ordered = models.BooleanField(default=False) become True

I have tried to add the context with the total sold but it didn't work so I kept it in the code below but commented it.

I have also tried to add a function with total count but I keep getting 'Item' object has no attribute 'order_set' I kept it below for reference

Here is the Item 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()

Here is the OrderItemmodels.py

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

Here is the Order

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

Here is the 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

Here is the template

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

This is the template when I tried to use the function for count_sold

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

Upvotes: 0

Views: 453

Answers (1)

Tiago Gomes
Tiago Gomes

Reputation: 377

Item doesn't have order_set, because there's no relation between those two Models.

  • Item is related to OrderItem
  • OrderItem is related to Order

Maybe you can try something like:

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()

and for the template

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

Upvotes: 1

Related Questions