2
我有以下型號:(即其中hasTopics
回報true
。)Django的查詢與聚合函數
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
s,它至少有一個連接的列表。 AFIK在Django中不可能使用filter
表達式中的實例方法(即像TopicLabel.objects.filter(TopicLabel.hasTopics).order_by('order')
這樣的東西是不可能的)。
什麼是正確的(Django風格)的方式來實現這樣的查詢(最好是獨立於數據庫)?
不要使用'count'來檢查是否存在。使用'queryset.exists()'insted。數據庫要容易得多。 count()可能有害。 – Pol
現在真的是您的問題的答案,但如果您的TopicLabelConnection模型純粹是爲了連接兩個其他模型,那麼您可以使用Django ManyToMany字段並讓它爲您生成和管理這些表。 –