Django Category and Subcategory searches

2019-03-13 19:21发布

I'm attempting to use a similar Category implementation to this one in the Django Wiki. I'm wondering what the Django way of doing a search to pull all objects associated with a parent category. For example, if I have a category "TV" and it has subcategories "LED", "LCD", and "Plasma", how would I be able to easily query for all TV's without recursively going through all subcategories and subsubcategories (if there are any).

Code wise I was thinking 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?

Thank you!

3条回答
Explosion°爆炸
2楼-- · 2019-03-13 19:51

Assuming you're using the Category model the same way it's being used on the page you referenced, it would seem that a category 'TV' would be a Category instance with a null parent, and 'Plasma' & 'LCD' would be Category instances with the 'TV' category 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 some items

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

Get the Item queryset

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

or

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

Does this look like it's in the ballpark of what you need?

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-03-13 19:51

If you are using django-categories, which uses MPTT then you can do the following:

Entry.objects.filter(category__in=category.get_descendants(True))
查看更多
forever°为你锁心
4楼-- · 2019-03-13 19:57

If you want to enforce strict categories and subcategories but also have the ability to perform fast searches with results like you describe, you may want to make a "tag" table where you don't actually allow users to tag items themselves, but rather as soon as you assign a category to an item you fill in the tag table for that item with all the parent categories up to the root node of the category tree.

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

The tag table would look something like:

   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 queryset will look like items=Item.objects.filter(tag='TV')

查看更多
登录 后发表回答