models.py
class Category(models.Model):
name = models.CharField(max_length=200)
slug = models.SlugField()
parent = models.ForeignKey('self', blank=True, null=True, related_name='child')
views.py
def category(request, parent, child):
c = Category.objects.filter(parent__isnull=True)
s = Category.objects.filter(parent__isnull=False)
if child == False:
p = Product.objects.filter(category__name__exact=parent)
return render_to_response('all_products.html', {'current_category': get_object_or_404(Category, name=parent), 'c':c, 'p':p, 's':s })
else:
p = Product.objects.filter(category__name__exact=child)
return render_to_response('all_products.html', {'current_category': get_object_or_404(Category, parent__name=parent, slug=child), 'c':c, 'p':p, 's':s })
urls.py
url(r'^products/(?P<parent>[-\w]+)/(?P<child>[-\w]+)/$', 'products.views.category'),
url(r'^products/(?P<parent>[-\w]+)/$', 'products.views.category', { 'child' : False }),
我正在为简单的两级类别应用构建视图。以上的作品我觉得它不是很干净,有什么改进的提示吗?
答案 0 :(得分:2)
我经常做以下事情:
models.py:您的“related_name”值应该是复数。 “孩子”让人很难理解发生了什么,而“child_set”则表明可能存在不止一个。
parent = models.ForeignKey('self', blank=True, null=True, related_name='child_set')
views.py:确保只搜索孩子的父类别
def category(request, parent, child=None):
parent = Category.objects.get(name=parent)
if child:
child = parent.child_set.get(name=child)
return render_to_response('all_products.html', {
'p': Product.objects.all(),
'c': parent,
's': child,
'current_category': child or parent,
})
urls.py:嵌套你的模式以利用DRY原则
view_prefix = 'products.views'
url_patterns = patterns('',
(r'^products/(?P<parent>[^/]+)/', include(patterns(view_prefix,
url(r'^$', 'category'),
url(r'^(?P<child>[^/]+)/$', 'category'),
))),
)