【问题标题】:How do I build an hyper linked field of nested relationships in Django Rest Framework?如何在 Django Rest Framework 中构建嵌套关系的超链接字段?
【发布时间】:2016-01-20 09:44:03
【问题描述】:

我有四个模型UserUserProfilePostUserPostUser 是 Django 自带的默认值。

UserUserProfile 具有一对一的关系。

UserPostPostUser 都有一个外键。

现在在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_setUserPosts 的列表。我不想使用字符串插值等手动构建 URL,那么我该如何解决这个问题?

【问题讨论】:

    标签: python django python-2.7 serialization django-rest-framework


    【解决方案1】:

    您可以在 UserPost 模型 FK 上添加一个 related_name 来发布:

    class UserPost(models.Model):
        post = models.ForeignKey(Post, related_name="userposts")
        ...
    

    并在您的 UserProfile 模型上添加 get_posts 方法:

    def get_posts(self):
        return Post.objects.filter(userposts__user=self.user)
    

    然后在您的序列化器字段中,您可以设置source="get_posts"

    您还可以通过UserPost 为您的Post 模型添加m2m:

    class Post:
        users = models.ManyToManyField(User, through=UserPost, related_name="posts")
        ...
    

    在这种情况下,您可以使用user.posts.all() 访问用户的帖子,因此您可以在序列化器字段中设置source="user.posts"

    【讨论】:

    • 除此之外还有什么办法吗?我没有对模型进行任何更改
    • 你不必为你的FK添加相关名称,尝试将get_posts方法中的查询集修改为Post.objects.filter(userpost__user=self.user)
    猜你喜欢
    • 1970-01-01
    • 2015-09-18
    • 1970-01-01
    • 2016-12-28
    • 1970-01-01
    • 1970-01-01
    • 2020-03-18
    • 1970-01-01
    • 2015-02-06
    相关资源
    最近更新 更多