models.py
class Category(models.Model):
image = models.ImageField(upload_to='book_images/category_images')
title = models.CharField('Назва', max_length=128)
slug = models.CharField(blank=True, max_length=128)
class Book(models.Model):
image = models.ImageField('Зображення', blank=False, upload_to='book_images')
title = models.CharField('Назва', max_length=128)
price = models.DecimalField('Ціна', max_digits=6, decimal_places=2)
author = models.ForeignKey(Author, on_delete=CASCADE, verbose_name='Автор')
edition = models.ForeignKey(Edition, on_delete=CASCADE, verbose_name='Видавництво')
category = models.ForeignKey(Category, on_delete=CASCADE, verbose_name='Категорія')
I want to display top 3 editions by count of their books. How can I do that?
CodePudding user response:
You can use inverse relationship with annotate like this :
from django.db.models import Count
top_3 = Edition.objects.annotate(nb_books=Count('book')).order_by('nb_books')[:2]
More info here