无法使用视图名称" 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
答案 0 :(得分:0)
序列化程序的字段应定义为序列化程序属性,而不是元属性:
class PostListSerializer(ModelSerializer):
url = HyperlinkedRelatedField(
view_name="posts-api:detail",
read_only=True,
lookup_field='slug'
)
class Meta:
...
此外,如果您需要获取帖子的网址而不是某些相关对象的网址,则应使用HyperlinkedIdentityField
:
class PostListSerializer(ModelSerializer):
url = HyperlinkedIdentityField(
view_name="posts-api:detail",
read_only=True,
lookup_field='slug'
)
class Meta:
fields = (
'id',
'url',
'user',
'title',
'content',
'created_at',
'updated_at',
)
model = Post
答案 1 :(得分:0)
无法使用视图名称“ posts-api:detail”解析超链接关系的URL。您可能没有在API中包含相关模型,或者在此字段上错误地配置了lookup_field
属性。
url = HyperlinkedIdentityField(view_name="posts-api:detail" ,read_only=True, lookup_field ='slug')
class Meta:
model = Post
fields = [
'url',
'user',
'id',
'title',
'slug',
'content',
]