Search code examples
djangodjango-modelsormannotationsdjango-queryset

Django ORM ForeignKey queryset output using annotations


I have the following 3 django models (using some abstractions):

class Person(models.Model):
    full_name = models.CharField(max_length=120, validators=[MinLengthValidator(2)])
    birth_date = models.DateField(default='1900-01-01')
    nationality = models.CharField(max_length=50, default='Unknown')

    class Meta:
        abstract = True


class Director(Person):
    years_of_experience = models.SmallIntegerField(validators=[MinValueValidator(0)], default=0)

    objects = DirectorManager()


class Actor(Person):
    is_awarded = models.BooleanField(default=False)
    last_updated = models.DateTimeField(auto_now=True)


class Movie(models.Model):
    MOVIE_GENRES = (
        ('Action', 'Action'),
        ('Comedy', 'Comedy'),
        ('Drama', 'Drama'),
        ('Other', 'Other')
    )

    title = models.CharField(max_length=150, validators=[MinLengthValidator(5)])
    genre = models.CharField(max_length=6, choices=MOVIE_GENRES, default='Other')
    rating = models.DecimalField(max_digits=3, decimal_places=1, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)], default=0)
    director = models.ForeignKey(Director, on_delete=models.CASCADE)
    starring_actor = models.ForeignKey(Actor, on_delete=models.SET_NULL, blank=True, null=True)
    actors = models.ManyToManyField(Actor, related_name="actors")

As you can see in the code above, I have also 1 manager. Here it is:

class DirectorManager(models.Manager):
    def get_directors_by_movies_count(self):
        return self.all().values("full_name").annotate(movies_num=Count("movie__director")).order_by("-movies_num", "full_name")

And here is my problem. I need and output like this:

<QuerySet [<Director: Francis Ford Coppola>, <Director: Akira Kurosawa>...>

instead, I am receiving this:

<QuerySet [{'full_name': 'Francis Ford Coppola', 'movies_num': 2}, {'full_name': 'Akira Kurosawa', 'movies_num': 1}...]>

So, I need just one record: Director, not these 2 full_name and movies_num, but i want to preserve the same group and order logic. How to do this?


Solution

  • Don't use .values(), it converts a model object into a dictionary, which is also a primitive obsession antipattern [refactoring.guru]:

    from django.db.models import Count
    
    
    class DirectorManager(models.Manager):
        def get_directors_by_movies_count(self):
            return self.annotate(movies_num=Count('movie')).order_by(
                '-movies_num', 'full_name'
            )