Reputation: 10765
I have a this model:
class Document(models.Model):
data = models.TextField()
users = models.ManyToManyField(User)
How would you convert the following query for the model above to raw sql?
Document.objects.annotate(num_users=Count(users))
I need to switch this to raw sql because there is a bug in django when using MySql that makes annotate very slow.
But I'm not sure how to handle the many to many field in raw sql..
Document.objects.raw('SELECT ...')
Upvotes: 1
Views: 3953
Reputation: 1072
you can get corresponding query the way mentioned below:
queryset = Document.objects.annotate(num_users=Count(users))
sql_query = queryset.query
print(sql_query)
Upvotes: 0
Reputation: 28489
The easiest way to translate your Django query to SQL is to simply look at the SQL that Django generates: How can I see the raw SQL queries Django is running?
Upvotes: 2