views:

38

answers:

1

I have a list of data. This data model has many-to-many fields to both a categories model and a keywords model. The data model itself has a name and description. The data can have multiple categories and keywords.

On the front end, the user can select a number of categories to filter down the data or do a search... So the data shown should be any data with any of the categories selected. If 'Test Data 1' has the category 'A' and 'Test Data 2' has the category 'B', if the user selects to see category 'A' and 'B', then both the pieces of data will show. The search is meant to search for data within the title, description and the keywords associated with the data, if any categories are selected, it will search within what data is left after the categories have been queried.

I'm not an expert at Django here... I'm trying to work out the best way to do this. I don't want to resort to using something like Haystack etc, as my data is pretty simple really. I've found that doing .filter() on objects is basically giving me an AND in the underlying SQL, which is not ideal for the way the categories work. It seems I need some sort of OR... maybe?

The category selection on the front end is done with a form and so the data that comes back is basically a list of the categories selected ['A', 'B', 'C']... is there no way I can drop that into a queryset in Django and returns all the data that has one or any of these categories?

Many thanks!

+1  A: 

Not sure what you mean here. You can try something along these lines:

from django.db.models import Q

query = 'fun'
books = Fun.objects.filter(Q(categories__id__in=[1,2,3]),
                     Q(name__icontains=query) | \
                     Q(description__icontains=query) | \
                     Q(keywords__title__icontains=query))

http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects

Louis
@Louis After reading this, and then doing more research based off this, it's really helped me out. Thank you. I just needed to see a working example like this to get my head around it. Thanks!
littlejim84