具有主键按位树状结构的django类别应用程序。
django-bit-categor的Python项目详细描述
Author: | Tomas Peterka |
---|---|
licence: | GPL |
抽象(和一个具体的)Model,具有使用按位id字段的树状结构。 这个实现是非常简单和超级快速! 给定一个类别,可以查询该类别的相关模型(产品) 所有的子类别 somemodel.objects.filter(category\u id\u gte=category.gte,category\u id\u lt=category.lt)
得到它
来源:https://github.com/katomaso/django-bit-category/ PYPI:https://pypi.python.org/pypi/django-bit-category/
技术细节
关键思想是在模型的id中为不同级别的 等级制度。在基本设置中,我们期望32位id(可以通过ID_BIT_WIDTH更改) 我们为每个级别提供5位(可以通过LEVEL_BIT_WIDTH更改)。 标识如下:
XXXXX000000000000000000000000000 # mask for the root category 00001000000000000000000000000000 # first root 00010000000000000000000000000000 # second root 00011000000000000000000000000000 # third root 00001000010000000000000000000000 # first child of the first root 00001000100000000000000000000000 # second child of the first root ...and so on
获取所有级别的all子体在hierarchical_instance.descendants, 但在引擎盖下,它很简单:
SomeModel.objects.filter(category_id__gte=category.gte, category_id__lt=category.lt)
此应用程序中包含的内容
- abstract HierarchicalModel which takes care about the magic with IDs
- abstract BaseCategory which contains the most usual category implementation
- HierarchicalField which you can use for any custom model
- HierarchicalWidget which dynamically (via AJAX) creates / deletes select boxes
- urls.py and views.py which contains AJAX magic for form field working
如何使其工作
如果您只想使用其中一个抽象模型,那么您不需要做任何特殊的事情。 导入抽象模型from bitcategory.models import BaseCategory,并在 具体模型。然后在另一个要使用类别的型号中制作外键:
# :file: models.py from django.db import models from bitcategory.models import BaseCategory class MyCategory(BaseCategory): # BaseCategory already provides fileds name, slug and path class Meta: abstract = False class MyProduct(models.Model): # some other fields like price, quantity .... category = models.ForeignKey('myproject.MyCategory', verbose_name=_("Category"))
这就是Model定义的全部内容。现在,假设您在 变量category,您可以通过以下方式查询类别及其所有子类别中的产品:
MyProduct.objects.filter(category_id__gte=category.gte, category_id__lt=category.lt)
或仅通过以下方式获取该类别的产品:
MyProduct.objects.filter(category=category)
但是,如果您想在表单中包含category的动态选择框, 您需要做更多
add the ^{tt9}$ into your INSTALLED_APPS
add ^{tt10}$ into your urls and specify your custom hierarchical model. If you didn’t create your custom hierarchical model, then use our pre-built concrete model ^{tt11}$. We do that in order to be able to respond to AJAX requests which are sent by the ^{tt12}$. The most simple way looks like:
# :file: urls.py from django.conf.urls import patterns, include, url from myapp.models import YourHierarchicalModel urlpatterns = patterns('', url('', include('bitcategory.urls'), {"model": YourHierarchicalModel}), )
现在您可以在表单中显示类别了。首先,添加 bitcategory.fields.HierarchicalField在表单中。将表单呈现为页面时,不要 忘记在javascripts模板中包含{{form.media}}。