我有以下模型:
class TopicLabel(models.Model):
name = models.CharField(max_length=256)
order = models.IntegerField(null=True, blank=True)
def __unicode__(self):
return self.name
def hasTopics():
return TopicLabelConnection.objects.filter(labelId=self.id).count() > 0
class TopicLabelConnection(models.Model):
topicId = models.ForeignKey(Topic, related_name='connection_topic')
labelId = models.ForeignKey(TopicLabel, related_name='connection_label')
def __unicode__(self):
return self.labelId.name + ' / ' + self.topicId.title
在某个 View 中,我想创建一个包含所有 TopicLabel
的列表,它们至少有一个连接(即 hasTopics
返回 true
).
据我所知,在 Django 中不可能在 filter
表达式中使用实例方法(即类似于 TopicLabel.objects.filter(TopicLabel.hasTopics).order_by('order')
是不可能的)。
实现此类查询的正确(Django 风格)方法是什么(最好是独立于数据库的)?
最佳答案
对于这种特定情况,您根本不需要聚合函数。使用 isnull
过滤器:
TopicLabel.objects.filter(connection_label__isnull=False)
对于确实需要聚合的情况,您可以按照 aggregation documentation 中的说明过滤注释.
关于python - 具有聚合函数的 Django 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18988194/