I have following models:
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
In a certain view I want to create a list of all TopicLabel
s, which have at least one connection (i. e. where hasTopics
returns true
).
AFAIK it is impossible in Django to use instance methods in filter
expressions (i. e. something like TopicLabel.objects.filter(TopicLabel.hasTopics).order_by('order')
is impossible).
What is the correct (Django-style) way to implement such query (preferably database-independent) ?
For this specific case, you don't need an aggregation function at all. Use an isnull
filter:
TopicLabel.objects.filter(connection_label__isnull=False)
For cases where you do need an aggregate, you can filter on annotations as described in the aggregation documentation.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments