Search by category and subcategory of Django

I am trying to use a similar implementation of this category in the Django Wiki. I am wondering how Django searches to pull out all the objects associated with the parent category. For example, if I have the category "TV" and it has subcategories "LED", "LCD" and "Plasma", how could I easily request for the entire TV without recursively going through all the subcategories and subcategories (if any) .

The code is wise I thought something like:

class Item(models.Model): name = ... ... category = models.ForeignKey(Category, null=True, blank=True) 

so with this type of implementation is there any easy way to do what i need, or is there any other better solution?

Thanks!

+7
django django-models django-queryset
source share
3 answers

If you want to apply strict categories and subcategories, but also be able to perform a quick search with the results as you describe, you can create a β€œtag” table where you actually do not allow users to mark elements themselves, but as soon as you assign a category to an element, you fill in the tag table for this element with all parent categories to the root of the node category tree.

For example, if you have the following: alt text http://img509.yfrog.com/img509/9845/photoho.jpg

The tag table will look something like this:

  id | tag_name | tv_id 1 | "tv" | 1 2 | "sd" | 1 3 | "crt" | 1 4 | "tv" | 2 5 | "HD" | 2 6 | "LCD" | 2 7 | "tv" | 3 8 | "HD" | 3 9 | "plasma" | 3 

Now your request will look like items=Item.objects.filter(tag='TV')

+8
source share

Assuming that you are using the Category model in the same way as it is used on the page that you linked to, it would seem that the category β€œTV” will be an instance of Category with zero parent Plasma 'and' LCD 'will be Category instances with the category β€œTV” in as a parent.

 >>> tv=Category(name="TV") >>> tv.save() >>> lcd=Category(name="LCD", parent=tv) >>> lcd.save() >>> plasma=Category(name="Plasma", parent=tv) >>> plasma.save() 

Create multiple items

 >>> vizio=Item(name="Vizio", category=lcd) >>> vizio.save() >>> plasmatron=Item(name="PlasmaTron", category=plasma) >>> plasmatron.save() 

Get an item selection request

 >>> items=Item.objects.filter(category__parent=tv) 

or

 >>>> items=Item.objects.filter(category__parent__name='TV') 

Does this mean that it looks like the stage of what you need?

+5
source share

If you use django categories that use MPTT, you can do the following:

 Entry.objects.filter(category__in=category.get_descendants(True)) 
0
source share

All Articles