我有以下模型,我需要知道有多少OtherModel实例指向同一个MyModel实例。
class MyModel(models.Model):
int = models.SmallIntegerField()
class OtherModel(models.Model):
other_model = models.ForeignKey(MyModel, null=True, blank=True)
int = models.SmallIntegerField()我可以使用for-循环,但是性能很差。还有其他方法可以选择所有的MyModel对象并在一个查询中获取相关的计数吗?
for m in MyModel.objects.all():
count = self.othermodel_set.count()发布于 2016-07-28 18:24:11
from django.db.models import Count
result = MyModel.objects.all().annotate(othermodel_count=Count('othermodel'))关于聚合特征的Django文档。
https://stackoverflow.com/questions/38644024
复制相似问题