2

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()

Paulo Boaventura
  • 1,365
  • 1
  • 9
  • 29
William55
  • 25
  • 5
  • Welcome to Stackoverflow! Your question is already answer in earlier posts ([1](https://stackoverflow.com/q/3748295/1660013), [2](https://stackoverflow.com/questions/971667/how-to-view-corresponding-sql-query-of-the-django-orms-queryset)). You may read [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) to improve your next questions. – Alireza Farahani Jul 10 '22 at 05:10
  • Does this answer your question? [How can I see the raw SQL queries Django is running?](https://stackoverflow.com/questions/1074212/how-can-i-see-the-raw-sql-queries-django-is-running) – Alireza Farahani Jul 10 '22 at 05:14

1 Answers1

1

try this:

queryset = Publisher.objects.annotate(num_books=Count('book')).order_by('-num_books')[:5]
print(str(queryset.query))
Divya Prakash
  • 898
  • 1
  • 6
  • 14
  • Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Jul 25 '22 at 10:23