Tech
Tech

Reputation: 945

QuerySet for 3 Connected Model

I have a tree model for my ecommerce project. Want to show which product and how many waiting for packaging. I just want to show New Orders' product and quantities.

For example:

A product - 119 B product - 6

my model is:

CHOICES = (
    (1, _("New Orders")),
    (9, _("Canceled")),
    (10, _("Completed")),

)

class Orders(models.Model):
    order_no = models.CharField(max_length=80)
    order_date = models.DateField(blank=True,null=True)
    order_status = models.IntegerField(choices=CHOICES, default=1)

    class Meta:
        verbose_name = "Order"
        verbose_name_plural = "Orders"
        ordering = ['order_date']


    def __str__(self):
        return self.order_no

class Products(models.Model):

    product_name = models.CharField(max_length=250,blank=True,null=True)
    barkod = models.CharField(max_length=60,blank=True,null=True)
    raf = models.CharField(max_length=15,blank=True,null=True)
    tax = models.DecimalField(blank=True,null=True, max_digits=5, decimal_places=0)

    class Meta:
        verbose_name = "Product"
        verbose_name_plural = "Products"
        ordering = ['pk']

    def __str__(self):
        return self.product_name

class OrderItems(models.Model):

    order = models.ForeignKey(Orders,on_delete=models.CASCADE,related_name='order')
    product = models.ForeignKey(Products,on_delete=models.PROTECT,related_name='product_order')
    quantity = models.CharField(max_length=6,blank=True,null=True)
    price = models.DecimalField(blank=True,null=True, max_digits=9, decimal_places=2)


    class Meta:
        verbose_name = "Item"
        verbose_name_plural = "Items"
        ordering = ['-pk']


    def __str__(self):
        return self.order.order_no

There is 3 model connected each other. I need the products in the New Orders and total quantity of them. I couldn't find the right way to do it. Is there a suggestion?

Upvotes: 0

Views: 45

Answers (1)

ruddra
ruddra

Reputation: 52018

You can try like this using group_by:

from django.db.models import Sum
OrderItems.objects.filter(order__order_status=1).values('product').annotate(total=Sum('quantity')).values('product__name', 'total')

Upvotes: 1

Related Questions