Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Search Many to Many Query

I'm trying to do a query a search with a ManyToMany Relationship, This is what I have so far:

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

Do you know how I can search the tags.title field in the query?

Here are the Models, I cleaned them up so they arent so long :)

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

Most of the questions I looked up are using filters and I'm no Django master so I am asking this hopefully not adding a duplicate question.

like image 624
JREAM Avatar asked May 17 '13 12:05

JREAM


Video Answer


2 Answers

Do it with the proper field_lookup: tags__title__icontains = search:

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

Fields lookups are very useful, you should take a look at the docs.

like image 159
Paulo Bu Avatar answered Oct 06 '22 00:10

Paulo Bu


You can do this using tags__title__icontains as

designs = designs.filter(Q(title__icontains = search) | 
                         Q(tags__title__icontains = search))
like image 36
Rohan Avatar answered Oct 05 '22 22:10

Rohan