简体   繁体   中英

How to use temp table count values into into the where query in Django Raw Sql?


I need to use raw sql in my django project. I'm using count command and then I associated it with as command like "the_count" but i got an error. The error like this, the_count does not exist. And my my code here,
 # First Model class AModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_lenth=100) # Second Model class BModel(models.Model): a_model = models.ForeignKey(AModel, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) query = 'SELECT "app_AModel"."id", (SELECT COUNT(*) FROM "app_BModel" INNER JOIN ON ("app_BModel"."user_id" = "app_AModel"."user_id") WHERE ("app_BModel"."a_model_id" = "app_AModel"."id")) AS "the_count" FROM "app_AModel" WHERE ("the_count" = 0)' BModel.objects.raw(query)

Thank you for yours helps...

From postgreSQL documentation

An output column's name can be used to refer to the column's value in ORDER BY and GROUP BY clauses, but not in the WHERE or HAVING clauses; there you must write out the expression instead.

Also you probably want to use GROUP BY and HAVING on my_app table instead so something in a line of following:

SELECT a_model_id, COUNT(*) from app_BModel GROUP BY a_model_id HAVING count(*) > 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM