N
N
NyxDeveloper2021-09-06 19:56:43
Django
NyxDeveloper, 2021-09-06 19:56:43

How to aggregate m2m fields and filter by aggregation results?

I need to make a simple, at first glance, filtering. There are two models with a one-to-many relationship:

class MyList(models.Model):
    name = models.CharField(verbose_name='Имя', max_length=100)

class MyListItem(models.Model):
    mylist = models.ForeignKey(MyList, verbose_name='Список', on_delete=models.CASCADE)
    name = models.CharField(verbose_name='Имя', max_length=100)
    weight = models.FloatField(verbose_name='Вес, кг')

The task is as simple as possible: using the method, you need to queryset.filter()filter objects MyListby the sum of the fields weightof objects MyListItemthat refer to it. I found a similar example in the official documentation on aggregate / annotate, so I decided to ask those who know. Is it possible to implement such filtering? How to do it?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question