我找到了这个,但我需要类似的东西
select count(*) as my_count from my_table;
在 Django 中可能吗?
谢谢。
例如,如果您有“Book”对象,只需转换 .count() 方法:
Book.objects.count()
假设您要进行聚合。Django ORM 可以做到。这是一个文档。
简而言之,您可以汇总一些计数,然后在查询中使用它。文档中的示例:
class Author(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
class Publisher(models.Model):
name = models.CharField(max_length=300)
num_awards = models.IntegerField()
class Book(models.Model):
name = models.CharField(max_length=300)
pages = models.IntegerField()
price = models.DecimalField(max_digits=10, decimal_places=2)
rating = models.FloatField()
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
pubdate = models.DateField()
class Store(models.Model):
name = models.CharField(max_length=300)
books = models.ManyToManyField(Book)
registered_users = models.PositiveIntegerField()
现在,当你这样做时:
>>> from django.db.models import Count
>>> pubs = Publisher.objects.annotate(num_books=Count('book'))
>>> pubs
SQL查询将如下:
SELECT "main_publisher"."id", "main_publisher"."name", "main_publisher"."num_awards", COUNT("main_book"."id") AS "num_books" FROM "main_publisher"LEFT OUTER JOIN "main_book" ON ("main_publisher"."id" = "main_book"."publisher_id") GROUP BY "main_publisher"."id", "main_publisher"."name", "main_publisher"."num_awards" LIMIT 21; args=()
您可以在过滤中使用聚合数据:
>>> pubs = Publisher.objects.annotate(num_books=Count('book')).filter(num_books=2)
>>> pubs
SELECT "main_publisher"."id", "main_publisher"."name", "main_publisher"."num_awards", COUNT("main_book"."id") AS "num_books" FROM "main_publisher"LEFT OUTER JOIN "main_book" ON ("main_publisher"."id" = "main_book"."publisher_id") GROUP BY "main_publisher"."id", "main_publisher"."name", "main_publisher"."num_awards" HAVING COUNT("main_book"."id") = 2 LIMIT 21; args=(2,)