【发布时间】:2016-01-20 09:44:03
【问题描述】:
我有四个模型User、UserProfile、Post 和UserPost。 User 是 Django 自带的默认值。
User 与UserProfile 具有一对一的关系。
UserPost 对Post 和User 都有一个外键。
现在在UserProfile 的序列化程序中,我想将用户的所有帖子都包含为超链接字段。我该怎么做?
以下失败:
class UserProfileSerializer(serializers.ModelSerializer):
id = serializers.IntegerField(source="user.id")
profile_picture = serializers.CharField(max_length=1000, allow_null=True)
posts = serializers.HyperlinkedRelatedField(
view_name='post-detail',
read_only=True, many=True, source="user.userpost_set.post")
我得到一个错误:
'RelatedManager' object has no attribute 'post'
显然因为userpost_set 是UserPosts 的列表。我不想使用字符串插值等手动构建 URL,那么我该如何解决这个问题?
【问题讨论】:
标签: python django python-2.7 serialization django-rest-framework