Home > Enterprise >  Django annotate count of disctinct values of the running quesyset in its children
Django annotate count of disctinct values of the running quesyset in its children

Time:03-03

I was tracing this bug for a while until I found the source I believe it's coming from, and I have been stuck here now. I have the following models below:

class ShopItem(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    store = models.ForeignKey(to=Store, on_delete=models.CASCADE)
    name = models.CharField(max_length=250)

class SelectedProduct(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name="products", null=True, blank=True)
    product = models.ForeignKey(ShopItem, null=True, blank=True, on_delete=models.SET_NULL)

class Order(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    store = models.ForeignKey(Store, on_delete=models.CASCADE, related_name="orders")
    status = models.PositiveIntegerField(choices=OrderStatus.choices, default=OrderStatus.CART)
    number = models.CharField(max_length=36, blank=True, null=True)

Lets say for example an order has 5 products, 3 of these products are of the same type (p1, p2, p3) as they reference same shop item; where are the other two products (p4, p5) are different since they reference different shop items.

I am trying to annotate how many same products exist on this order as in the following

products = order.products.all().annotate(quantity=Count("product"))

Attempting to get a queryset of these products with quantity annotated, only thing, I get quantity of 1 for all products, where I am trying to get:

p1.quanity
> 3
p2.quanity
> 3
p3.quanity
> 3
p4.quanity
> 1
p5.quanity
> 1

is there anyway I could achieve this? I appreciate any insights!

CodePudding user response:

You should annotate the ShopItems, so:

products = ShopItem.objects.filter(
    selectedproduct__order=order
).annotate(
    quantity=Count('selectedproduct')
)

This will produce a QuerySet of ShopItems that is at least ordered once, and with quantity the number of SelectedProducts for that order and that ShopItem.

  • Related