具有聚合函数的Django查询

2024-10-01 09:35:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下型号:

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

在某个视图中,我想创建一个所有TopicLabel的列表,它们至少有一个连接(即hasTopics返回{})。在

AFAIK在Django中不可能在filter表达式中使用实例方法(例如,TopicLabel.objects.filter(TopicLabel.hasTopics).order_by('order')之类的东西是不可能的)。在

实现这种查询的正确(Django风格)方法是什么(最好是独立于数据库的)?在


Tags: nameselftruemodelreturnmodelsdefunicode
1条回答
网友
1楼 · 发布于 2024-10-01 09:35:30

对于这种特定的情况,您根本不需要聚合函数。使用isnull筛选器:

TopicLabel.objects.filter(connection_label__isnull=False)

对于确实需要聚合的情况,可以按aggregation documentation中所述过滤注释。在

相关问题 更多 >