How can I use the Django 1.8 ORM to count, how many members an object has?
For example: How can I SORT all workers by the count of the software, their company is using?
- Bill 3 (Windows, Office, Visio)
- Tom 2 (Windows, Office)
- Anton 1 (Office)
- Peter 0
- Stephan 0
Code:
def Software(model.Model):
name = models.CharField(max_length=200)
def Company(models.Model):
software = models.ManyToManyField(Software)
def Worker(models.Model):
company = models.ForeignKey(Company)
software = Software.objects.filter(price>60) # [<Software: Windows>,...]
workers = Worker.objects.filter(company__software__in=software).
annotate(software_count=Count('company__software‘))
for worker in workers:
print „%s %s (%s)" % (worker.name, worker.software_count, ...)
The tricky part is that I don’t want to filter BUT ONLY want to annotate the count of the software, used of the given list.
Any help is appreciated :-)