# 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.