简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM