我有2个型号的分类和产品。
类别包含多个产品,而产品可以包含多个类别。 一个类别对自己有一个FK。
`class Product(models.Model):
categories = models.ManyToManyField(Category, related_name='products')
class Category(models.Model):
parent = models.ForeignKey('self', blank=True, null=True, verbose_name='parent category', on_delete=models.CASCADE)`
对于我需要的模板:
我使用的是基于类的视图,我不知道该类的model
属性使用哪个,因为:
RawQuerySet' has no len()
答案 0 :(得分:1)
您应该将模型设置为Product
,因为那是您实际上正在查看和分页的模型。您的视图类应该类似于以下答案:https://stackoverflow.com/a/41297420/769971
型号:
class Product(models.Model):
categories = models.ManyToManyField(Category, related_name='products')
class Category(models.Model):
parent = models.ForeignKey('self', blank=True, null=True, verbose_name='parent category', related_name='children', on_delete=models.CASCADE)
您还需要更改get_queryset
以过滤类别PK。这是我认为应该是这样的:
def get_children_recursive(parent_category):
children = parent_category.children.all() # This depends on adding related_name to Category
for child in children:
children += get_children_recursive(child)
return children
class ProductListView(ListView):
paginate_by = 10
template_name = 'templates/your_product_view.html'
model = Product
context_object_name = 'products'
def get_queryset(self):
category = Category.objects.get(id=self.kwargs['category_id'])
all_children = get_children_recursive(category)
return Product.objects.filter(categories=all_children)
category_id
应该来自网址,在您的网址文件中应该如下所示:
urlpatterns = patterns('',
(r'^products/(?P<category_id>\d+)/$', ProductListView.as_view()),
)