Skip to content
Advertisement

How to perform translation from RAW SQL to django queryset

I am struggling with conversion to django query having raw sql I am new in django and any help will be appreciated

There are simple models:

Winemaker – target model

Wine

Post

Winemaker has 1+ Wines

Wine has 1+ Posts

I know that it should be done with annotations but have no idea how to implement it.

Advertisement

Answer

You should be able to accomplish this with a Count aggregation expression in an annotate function. I took a guess at your related_name values on your relationship fields, so the following code may not plug in directly, but should give you an idea of how to do what you want.

You may need to supply distinct=True depending on if you’re crossing relationships.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement