brsbilgic
brsbilgic

Reputation: 11843

Django search query for models with tags

I have models as below and I would like to select IndexedLibrary objects depending on its book name and the tag names of that book.

How can I build this query? The query below performs without including tags of the book, but I would like to join them also

IndexLibrary.objects.filter(book__name__icontains=KEYWORD)


class IndexedLibrary(models.Model):
    name = models.CharField(max_length=1000)
    book = models.ForeignKey(Book,null=False,blank=False)    

    def __unicode__(self):
        return self.name

class Book(models.Model):
    name = models.CharField(max_length=1000)

    def __unicode__(self):
        return self.name

class BookTag(models.Model):
    name = models.CharField(max_length=1000)
    book = models.ForeignKey(Book,null=False,blank=False)    
    def __unicode__(self):
        return self.name

Upvotes: 1

Views: 2836

Answers (1)

Matt Williamson
Matt Williamson

Reputation: 40233

I would add tags as a ManyToManyField(Tag, blank=True), remove the book property from BookTag and then query like

IndexLibrary.objects.filter(book__name__icontains=KEYWORD, \
    tags__name__in=['Tage Name 1', 'Tag Name 2'])

Especially since tags are often shared among more than one object.

Upvotes: 7

Related Questions