Two variables in a django url
models.py
class Category(models.Model):
name = models.CharField(max_length=开发者_StackOverflow200)
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 }),
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?
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.
parent = models.ForeignKey('self', blank=True, null=True, related_name='child_set')
views.py: Make sure you only search the parent category for the child
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: Nest your patterns to leverage the DRY principle
view_prefix = 'products.views'
url_patterns = patterns('',
(r'^products/(?P<parent>[^/]+)/', include(patterns(view_prefix,
url(r'^$', 'category'),
url(r'^(?P<child>[^/]+)/$', 'category'),
))),
)
精彩评论