Number of items in a Django field

models.py

class Event(models.Model):
    name = models.CharField(max_length=20, unique=True)
    distance = models.IntegerField()
    date = models.DateField()

class Category(models.Model):
    name = models.CharField(max_length=20, unique=True)
    description = models.CharField(max_length=20, unique=True)
    isnew = models.BooleanField(default=False)

class Result(models.Model):
    event = models.ForeignKey(Event)
    category = models.ForeignKey(Category)
    score = models.IntegerField()

I want to make a query to return the amount of each unique category in the result table for a given event.

What I'm doing now is something like:

results = Result.objects.filter(event=myevent)
categorycountdict = {}
for r in results:
    if r.category in categorycountdict:
        categorycountdict[r.category] += 1
    else:
        categorycountdict[r.category] = 1

Is there a better way, perhaps using a query instead of python.

+4
source share
3 answers

You can use annotate()with values(). This approach is shown in the docs for values(). To get a counter for each category, you can do:

from django.db.models import Count

categories = Result.objects.filter(
    event=myevent,
).order_by('category').values(
    'category__name'
).annotate(count=Count('category__name'))

This will return a list of dictionaries with keys category__nameand count, for example:

[{'count': 3, 'category__name': u'category1'}, {'count': 1, 'category__name': u'category2'}]

You can convert this into a single dictionary using a dictionary understanding:

counts_by_category = {d['category__name']: d['count'] for f in categories}
+5
source

annotate:

from django.db.models import Count

Results.objects.filter(event=some_event).annotate(Count('category'), distinct=True)
0

python collections.Counter:

results = Result.objects.filter(event=myevent).select_related('category')
c = Counter(r.category for r in results)

c - dict, , - .

, . , , , , .

select_related , . 1 python .



, ManyToManyField , .

"--" .

through Django ( ManyToManyField):

class Event(models.Model):
    name = models.CharField(max_length=20, unique=True)
    distance = models.IntegerField()
    date = models.DateField()
    categories = models.ManyToManyField(Category, through='Result', related_name='events')

In your code for this event, you can request the following:

event.categories.count()

Whereas Alasdair note:

event.categories.values('pk').annotate(count=Count('pk'))
0
source

Source: https://habr.com/ru/post/1654705/


All Articles