我有以下型号:
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风格)方法是什么(最好是独立于数据库的)?在
对于这种特定的情况,您根本不需要聚合函数。使用
isnull
筛选器:对于确实需要聚合的情况,可以按aggregation documentation中所述过滤注释。在
相关问题 更多 >
编程相关推荐