vincentf
vincentf

Reputation: 1499

How do I make efficient queries in Django?

I have the following models, which are relative to Django's built in models Tag and Site. Given a Site, what is the most efficient way to query all the related Tags

class InlineTag(models.Model):
    tag = models.ForeignKey(Tag, null=False)
    topic = models.ForeignKey(Topic, null=False)
    order = models.PositiveIntegerField(null=False, blank=True)

class Topic(models.Model):
    description = models.CharField(max_length=255, blank=False)
    sites = models.ManyToManyField(Site)

I'm doing this way currently, it seems too complex:

tags = []
current_site = Site.objects.get_current()
topics = Topic.objects.filter(sites=current_site)

for topic in topics:
    inline_tags = InlineTag.objects.filter(topic=topic)

    for inline_tag in inline_tags:
        tags.append(inline_tag.tag)

Upvotes: 1

Views: 73

Answers (1)

solarissmoke
solarissmoke

Reputation: 31484

You can use reverse foreign key lookups to get all the tags in one query:

tags = Tag.objects.filter(inlinetag__topic__sites=current_site).distinct()

The distinct() ensures that you don't get duplicate results, e.g., if a site has multiple topics that share the same tags.

As a side note, Django doesn't have a built-in Tag model - presumably you are using a third-party app for that.

Upvotes: 1

Related Questions