1

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) ?

2
  • 4
    Don't use count to examine existence. use queryset.exists() insted. It is much easier for your database. count() can be harmful. Commented Sep 24, 2013 at 17:39
  • Now really an answer to your question but if your TopicLabelConnection model exists purely to connect two other models then you could probably use the Django ManyToMany field and have it generate and manage the tables for you. Commented Sep 24, 2013 at 21:01

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.