InvictusManeoBart
InvictusManeoBart

Reputation: 383

how to find much matches of one objects from one queryset in another queryset Django?

how to find many matches with one object from the set of queryset objects (which contain one search object) in another many queryset django objects

for example, how to find the most frequent product in order products and deduce its quantity

I apologize for such a question, I'm still noob and my brains can not so critical think

order models

class Order(models.Model):                  
    products_of_order = models.ManyToManyField("ProducInOrder", related_name='Some_Products')

class ProducInOrder(models.Model):
    order = models.ForeignKey(Order, blank=True, null=True, default=None)
    product = models.ForeignKey(Product, blank=True, default=None)
    quantity = models.IntegerField(default=0)

product models

class Product(models.Model):
        name_of_product = models.CharField(max_length=20)

i try to do this:

 product = Product.objects.all()
 some  = Order.objects.filter(products_of_order__product__in=product).count()

but it's just return all product which contain in order products, how to get count each product in orders products which matches with list of products.

i have one idea how to make it but i wanna make it in one line) in one queryset)

some_dict = {}
for i in some:
    for s in i.products_of_order.all():
        if s.product.name_of_product in some_dict:
            some_dict.s.product.name_of_product += 1
        else:
            some_dict.s.product.name_of_product = 1

Upvotes: 0

Views: 196

Answers (1)

J_H
J_H

Reputation: 20450

It's not clear what you're asking. But that last piece of code would be expressed more naturally using defaultdict:

count = collections.defaultdict(int)
for order in some:
    for product in order.products_of_order.all():
        count[product.name] += 1

Upvotes: 0

Related Questions