How to convert from django orm to sql query?
Publisher.objects.annotate(num_books=Count('book')).order_by('-num_books')[:5]
in sql query?
class Publisher(models.Model):
name = models.CharField(max_length=300)
class Book(models.Model):
name = models.CharField(max_length=300)
pages = models.IntegerField()
price = models.DecimalField(max_digits=10, decimal_places=2)
rating = models.FloatField()
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)
pubdate = models.DateField()
try this:
queryset = Publisher.objects.annotate(num_books=Count('book')).order_by('-num_books')[:5]
print(str(queryset.query))