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 TopicLabels, 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) ?
countto examine existence. usequeryset.exists()insted. It is much easier for your database.count()can be harmful.