简体   繁体   中英

In Django, how could I in a single query get total row count based on distinct field values?

This seems like a scenario that would be pretty common, so I'm really hoping someone might have a quick answer for me.

Consider the scenario where I have multiple sites and multiple companies per site for which I am gathering leads. So I have a lead table where each record has the following fields: date , site , companies (a lead can go to multiple companies), user , comment . Now I need to generate a summary the gives the total number of leads that each company got on each site for each date.

So basically I need a query that will give me the total number of rows for each company on each site. Is this even possible to do in a single query?

Alternatively, we can easily loop through the sites, in which case we would only need to count the number of rows that belonged to each company, given a particular site.

Appreciate any thoughts. Here's a sample model to work with:

class Lead(models.Model):
    date = models.DateTimeField(auto_now_add=True)
    site = models.ForeignKey(Site)
    companies = models.ManyToManyField(Company)
    user = models.ForeignKey(User)
    comment = models.TextField()

So I've been fiddling around with this, and I believe I have come up with a solution that produces the results I'm after. Given the model above, I'm using the following:

Lead.objects.values('site', 'companies').annotate(Count('id'))

This yields a list of dictionaries, one dictionary per unique site/company combination, each containing an id__count key that contains the total number of rows for that particular combination of site and company. And if one lead has multiple companies associated with it, a separate dictionary is produced for each.

In our actual model, we have different types of leads as well and an additional field type . So if I wanted to take that into consideration as well, I would simply add a type field to the model and use the following:

Lead.objects.values('site', 'companies', 'type').annotate(Count('id'))

Using this, I would get one dictionary per site, per type, per company, each with its own count. Django is pretty smart!

Anyway, basic question I'm sure, but I couldn't quite find anything that addressed it. Hope this helps someone.

You can use the distinct queryset method.:

Lead.objects.distinct('companies', 'site', 'date').count()

You can pass what ever field ( or fields ) into distinct to get a distinct records in that row. Then you can simply call count on it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM