1

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 ...')

2 Answers 2

2

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?

Sign up to request clarification or add additional context in comments.

1 Comment

Be careful! Maybe the bug he is talking about is how django translate that query to mysql syntax (although i hardly believe this query is treated differently in different DBMSs like postgre or mysql). If @9-bits feels that the raw query continues working slowly, he should add here the raw sql that django throws...
0

you can get corresponding query the way mentioned below:

queryset = Document.objects.annotate(num_users=Count(users))  
sql_query = queryset.query
print(sql_query)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.