【发布时间】:2018-11-22 00:58:30
【问题描述】:
无法使用视图名称“post-detail”解析超链接关系的 URL。您可能没有在 API 中包含相关模型,或者在此字段上错误地配置了 lookup_field 属性。
Serializers.py
post_detail_url = HyperlinkedRelatedField(
view_name="posts-api:detail",
read_only=True,
lookup_field='slug'
)
class PostListSerializer(ModelSerializer):
class Meta:
url = post_detail_url
fields = (
'id',
'url',
'user',
'title',
'content',
'created_at',
'updated_at',
)
model = Post
Urls.py
urlpatterns = [
url(r'^$', PostListAPIView.as_view(), name='list'),
url(r'^create/$', PostCreateAPIView.as_view(), name='create'),
url(r'^(?P<slug>[\w-]+)/$', PostDetailAPIView.as_view(), name='detail'),
url(r'^(?P<slug>[\w-]+)/edit/$', PostUpdateAPIView.as_view(), name='update'),
url(r'^(?P<slug>[\w-]+)/delete/$', PostDeleteAPIView.as_view(), name='delete'),
]
后模型
class Post(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, default=1)
title = models.CharField(max_length=200)
content = models.TextField()
posted = models.DateField(db_index=True, auto_now_add=True)
slug = models.SlugField(max_length=100, unique=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
【问题讨论】:
-
你需要在json响应中获取当前帖子的url吗?
-
我已经将反应设置作为我的前端来显示数据。到目前为止,我只是设置后端 rest-api 来查看 json 响应。所以是的,当前帖子将显示为 json 响应。
-
可以添加post模型吗?
-
添加了帖子模型。
标签: django django-models django-rest-framework django-views