9

我正在尝试使用多对多关系进行查询,这就是我目前所拥有的:

designs = designs.filter(Q(title__icontains = search) | 
                         Q(tags__icontains = search))

你知道我如何在查询中搜索 tags.title 字段吗?

这是模型,我清理了它们,所以它们不会太长:)

class Design(models.Model):
    title = models.CharField(max_length = 50, default = "")
    slug = models.SlugField(unique = True)   
    user = models.ForeignKey(User, related_name = "design_user")
    description = models.TextField()
    tags = models.ManyToManyField(to = Tags)

class Tags(models.Model):
    title = models.CharField(max_length = 50, unique = True)

    # Allows the category to list as a dropdown in the admin
    def __unicode__(self):
        return self.title

我查找的大多数问题都在使用过滤器,而且我不是 Django 大师,所以我希望不要添加重复的问题。

4

2 回答 2

11

使用正确的field_lookup: tags__title__icontains = search:

designs = designs.filter(Q(title__icontains = search) | 
                         Q(tags__icontains = search)  |
                         Q(tags__title__icontains = search))

字段查找非常有用,您应该查看文档

于 2013-05-17T12:59:15.083 回答
1

您可以使用tags__title__icontainsas

designs = designs.filter(Q(title__icontains = search) | 
                         Q(tags__title__icontains = search))
于 2013-05-17T12:59:05.933 回答