开发者

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.f开发者_开发百科ilter(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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜