B
B
bituke2021-10-05 14:52:26
Django
bituke, 2021-10-05 14:52:26

How to sort objects by model function?

the model has a many-to-many relationship, I want to sort this model in the view by the number of related collections.

class Genre(models.Model):
  '''Жанр фильма'''
  name = models.CharField(max_length=255)
  slug = models.SlugField(blank=True)

  def __str__(self):
    return self.name

  def save(self):
    self.slug = slugify(unidecode(self.name))
    super(Genre, self).save()

  def get_count_collections(self):
    collections = self.collections_genre.all().count()
    return collections

the get_count_collections function returns the count of related Genre model objects, what I am trying to do is:
all_genres = Genre.objects.all().order_by('get_count_collections')[:5]

what does not work by itself, you need a working solution. I will be grateful for any help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2021-10-05
@bituke

Remove the function and use the annotation .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question