django url 中的两个变量
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 }),
我正在为一个简单的两级类别应用程序构建一个视图。上面的作品我只是认为它不是很干净,有什么改进的建议吗?
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]+)/
I'm building a view for a simple two level category app. The above works I just don't think it's very clean, any tips for improving it?
, 'products.views.category'),
url(r'^products/(?P<parent>[-\w]+)/
I'm building a view for a simple two level category app. The above works I just don't think it's very clean, any tips for improving it?
, 'products.views.category', { 'child' : False }),
I'm building a view for a simple two level category app. The above works I just don't think it's very clean, any tips for improving it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我经常执行以下操作:
models.py:您的“lated_name”值应该是复数。 “child”让人很难理解发生了什么,而“child_set”则清楚地表明可能有多个。
view.py:确保只在父类别中搜索子
urls.py:嵌套您的模式以利用 DRY 原则
Frequently I do the following:
models.py: Your "related_name" value is supposed to be plural. "child" makes it hard to understand what is going on, while "child_set" makes it clear that there could be more than one.
views.py: Make sure you only search the parent category for the child
urls.py: Nest your patterns to leverage the DRY principle