pythondjangodjango-search-lucene

Django : Searching from different tables in django


I am trying to implement search functionality for the user in Django.

I can use Q for one table search but here the scenerio is different.

Here are my models:

Class Profile(models.Model)        
    name = models.OnoeToOneField(User)
    category = models.ForeignKey(Category)
    Tags   = models.ForeignKey(Tags)

class Category(models.Model)
    name = models.Charfield(max_length = 100)
    sub_cat =  models.ForeignKey(SubCategory)

I want to search a user who belongs to a categoey and/or a tag

But I am unable to find a way to do this. I don't want to use Haystack or Whoosh.

Please suggest to me some simple way to achieve this.


Solution

  • Did you try such a queryset ?

    User.objects.filter(
        Q(profile__category__name__icontains=search_string) |
        Q(profile__Tags__name__icontains=search_string)
    ).distinct()
    

    See complex lookups with Q objects for details.

    Note that I'm using distinct() to eliminate duplicate results because the same user can be selected for two reasons (each corresponding to a Q object).

    (Of course, you should adapt Tags__name which I put as is for the sake of the example, but I don't have the source of the Tags model).