Django类别和子类别搜索 [英] Django Category and Subcategory searches

查看:113
本文介绍了Django类别和子类别搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用类似的类别实现来在Django Wiki中这一个。我想知道Django的方法是如何进行搜索来拉取与父类相关联的所有对象。例如,如果我有一个类别电视,它有子类别LED,液晶和等离子,我如何可以轻松地查询所有电视,而无需递归地遍历所有子类别和子类别(如果有是否有)



明智的代码我在想:

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

所以这种类型的实现有什么简单的方法来做我需要的,还是有其他更好的解决方案? / p>

谢谢!

解决方案

如果要强制执行严格的类别子类别,但也可以使用您所描述的结果执行快速搜索的功能,您可能想要制作一个标签表,您不会在其中允许用户自己标记项目,而是一旦将类别分配给您填写标签标签的项目对于该项目,其所有父类别都为类别树的根节点。



例如,如果您具有以下内容:
alt text http://img509.yfrog.com/img509/9845/photoho.jpg



标签表看起来像:

  id | tag_name | tv_id 
1 | 电视| 1
2 | sd| 1
3 | crt| 1
4 | 电视| 2
5 | 高清| 2
6 | LCD| 2
7 | 电视| 3
8 | 高清| 3
9 | 等离子体| 3

现在,您的查询器将看起来像 items = Item.objects.filter tag ='TV')


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!

解决方案

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

这篇关于Django类别和子类别搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆