我正在开发一个Comment应用程序,我希望我的Commenterializer显示每个Comment实例的确切URL。我知道我必须使用Comment模型的get_absolute_url。但是我无法将我的视图名称从路由器连接到get_absolute_url。
这是我的模特:
class Comment(models.Model):
content = models.TextField(max_length=150)
author = models.ForeignKey(
User,
on_delete = models.CASCADE
)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField(blank=True)
content_object = GenericForeignKey('content_type', 'object_id')
parent = models.ForeignKey(
"self",
on_delete = models.CASCADE,
blank=True,
null=True
)
datestamp = models.DateTimeField(auto_now_add=True)
objects = CommentManager()
def __str__(self):
return str(self.content[:30])
def save(self):
self.object_id = self.parent.id
super(Comment, self).save()
def children(self):
return Comment.objects.filter(parent=self)
def get_absolute_url(self):
return reverse("comments-details", args=[str(self.id)])
@property
def is_parent(self):
if self.parent is None:
return False
return True
这是我的路由器:
router = router = routers.SimpleRouter()
router.register('api/comments', CommentViewSet)
urlpatterns = router.urls
如您所见,我正在尝试使用“注释详细信息”作为视图名称。 最终目标是显示这样的JSON:
{ url : 'blabla/comments/{pk}/details }
答案 0 :(得分:1)
好的,很容易解决。只需使用HyperlinkedModelSerializer,然后将“ url”添加到您的字段中即可:
class CommentSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Comment
fields = [
"url",
"datestamp",
"content",
"is_parent",
"object_id",
"children"
]