如何在 django 中嵌套 url 调用?例如,如果我有两个模型定义为
class Post(models.Model):
title = models.CharField(max_length=50)
body = models.TextField()
created = models.DateTimeField(auto_now_add=True, editable=False)
def __unicode__(self):
return self.title
@property
def comments(self):
return self.comment_set.all()
class Comment(models.Model):
comment = models.TextField()
post = models.ForeignKey(Post)
created = models.DateTimeField(auto_now_add=True)
使用以下 url 文件
根网址
urlpatterns = patterns('',
url(r'^post/', include('post.urls')),
)
发布网址
urlpatterns = patterns('',
url(r'^$', views.PostList.as_view()),
url(r'^(?P<pk>[0-9]+)/$', views.PostDetail.as_view()),
url(r'^(?P<pk>[0-9]+)/comments/$', include('comment.urls')),
)
评论网址
urlpatterns = patterns('',
url(r'^$', CommentList.as_view()),
url(r'^(?P<pk>[0-9]+)/$', CommentDetail.as_view()),
)
但是当我转到 /post/2/comments/1 时,我得到一个 Page not found 错误说明
Using the URLconf defined in advanced_rest.urls, Django tried these URL patterns, in this order:
^post/ ^$
^post/ ^(?P<pk>[0-9]+)/$
^post/ ^(?P<pk>[0-9]+)/comments/$
The current URL, post/2/comments/1, didn't match any of these.
虽然当我访问 /post/2/comments 时这不是问题 django 不允许这样嵌套 URL 调用吗?