0

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.

johnsyweb
  • 136,902
  • 23
  • 188
  • 247
masterofdestiny
  • 2,751
  • 11
  • 28
  • 40
  • "Now want to search a user with name for a category and a tag ." Could you rephrase and elaborate ? – jpic Feb 13 '13 at 08:15

2 Answers2

1

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).

jpic
  • 32,891
  • 5
  • 112
  • 113
1

It's very easy in fact:

Filter with category name:

Profile.objects.filter(category__name__iexact='category 1')

Filter with category id:

Profile.objects.filter(category__pk=27)

Filter with sub category name:

Profile.objects.filter(category__sub_cat__name__iexact='exact sub category name')
scriptmonster
  • 2,741
  • 21
  • 29