9-bits
9-bits

Reputation: 10765

Django raw sql query

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

Answers (2)

Naveen Jain
Naveen Jain

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

kdt
kdt

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

Related Questions