[英]django using mptt and polymorphic for model
I have a PolymorphicMPTTModel and models are: 我有一个PolymorphicMPTTModel,模型是:
class AbstractCategory(PolymorphicMPTTModel):
name = models.CharField(max_length=100)
parent = PolymorphicTreeForeignKey('self', null=True, blank=True,
related_name='sub_categories')
class Category(AbstractCategory):
def get_fields(self):
pass
class FakeCategory(AbstractCategory):
def get_fields(self):
pass
class AbstractProductModel(PolymorphicModel):
name = models.CharField(max_length=100)
class ProductModel(AbstractProductModel):
category = models.ForeignKey('category.Category', related_name='product_models')
class FakeProductModel(AbstractProductModel):
category = models.ForeignKey('category.AbstractCategory', related_name='fake_product_models')
Assume i have 3 objects of Category : Digital, Mobile-->Digital, Camera-->Digital. 假设我有3个类别的对象:数字,移动 - >数字,相机 - >数字。 Digital is parent of Mobile and Camera and this is simple example of tree structure.
Digital是Mobile和Camera的父母,这是树结构的简单例子。 I want to get all models that their category is Digital or sub category of Digital like Mobile or Camera.
我想得到他们的类别是数字的所有型号或像移动或相机的数字子类别。 for that i'm using:
因为我正在使用:
category = Category.objects.get(name='Digital')
descendants = category.get_descendants(include_self=True)
models = ProductModel.objects.filter(category__in=descendants).all()
I get this error: Cannot resolve keyword 'abstractcategory_ptr' into field. 我收到此错误: 无法将关键字'abstractcategory_ptr'解析为字段。 Choices are: category, ...
选择是:类别,......
and can't find the reason. 而且找不到原因。
While I don't quite understand why the category__in
filter breaks (it should work!), you can implement this query in a much better way. 虽然我不太明白为什么
category__in
过滤器中断(它应该工作!),你可以更好地实现这个查询。 When you join using the mptt fields, everything happens in a single query instead of a WHERE x IN (SELECT ..)
subquery. 当您使用mptt字段加入时,所有内容都发生在单个查询中而不是
WHERE x IN (SELECT ..)
子查询中。
class ProductModelQuerySet(PolymorphicQuerySet):
def get_descendants(self, category, include_self=False):
# narrow one level deeper for include_self=False effect
narrow = 0 if include_self else 1
# MPTT optimization, no need for a subquery.
return self.filter(
category__tree_id=category.tree_id,
category__lft__gte=category.lft + narrow,
category__rght__lte=category.rght - narrow,
)
and you can query that using: 你可以使用以下方式查询:
models = ProductModel.objects.get_descendants(category)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.