【问题标题】:Django db field not displaying modified slug field value after serializing序列化后 Django db 字段不显示修改后的 slug 字段值
【发布时间】:2021-09-23 02:15:16
【问题描述】:

我正在尝试在 Comment 类的 created_by 字段中获取用户名而不是用户 ID。我的模型如下:

class Comment(models.Model):
    thread_id = models.ForeignKey(Thread, on_delete=models.CASCADE)
    content = models.TextField()
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    likes = models.IntegerField(default=0)

在序列化器中使用了 slugfield。

class CommentSerializer(serializers.ModelSerializer):
    created_by = serializers.SlugRelatedField( 
                        slug_field='email',
                        queryset=User.objects.all())
    class Meta:
        model = Comment
        fields = ("id", "thread_id", "content", "created_by", "created_at", "likes")

在下面的 api 中,字段 created_by 仍然有用户 ID 而不是电子邮件。

 @action(detail=True, methods=["GET"])
    def list_comments(self, request, pk):
        comments = Comment.objects.filter(
            thread_id = pk
        )
        data = json.loads(serialize('json', comments))
        print("**************data**************")
        print(data)
        return Response(data, status.HTTP_200_OK)

打印出来的数据是这样的:

[{'model': 'blog.comment', 'pk': 20, 'fields': {'thread_id': 19, 'content': 'hi', 'created_by': 2, 'created_at': '2021-07-14T03:34:11.333Z', 'likes': 0}}]

这是因为序列化吗?如何正确获取 created_by 的值作为用户电子邮件而不是 id ?

【问题讨论】:

    标签: django field slug json-serialization


    【解决方案1】:

    在序列化器上使用 to_representation() 方法

    def to_representation(self, instance):
        rep = super(CommentSerializer, self).to_representation(instance)
        rep['created_by'] = instance.created_by.email
        return rep
    

    【讨论】:

    • 谢谢你。这在我调用内置 API 时有效。当我点击此网址(内置 API):0.0.0.0:8004/blog/api/comment 时,下面是按预期显示的 created_by 字段数据。 { "id": 19, "content": "comment content", "created_at": "2021-07-14T03:13:31.284656Z", "likes": 0, "thread_id": 20, "created_by": "abc@gmail.com" }
    • 当我点击我编写的自定义 API 的 url(0.0.0.0:8004/blog/api/comment/19/list_comments) 时,如下所示:{ action(detail=True, methods=["GET"]) def list_comments(self, request, pk): comments = Comment.objects.filter( thread_id = pk ) for comment in comments: print(comment.created_by) data = json.loads(serialize('json', comments)) print(data) return Response(data, status.HTTP_200_OK) } created_by 字段仍然带有 id:“created_by”:5跨度>
    • 您没有在自定义操作中使用您的序列化程序,请尝试:'serializer = CommentSerializer(cmets, many=True) return Response(serializer.data)'
    • 谢谢。这行得通。过滤后的数据适当地显示 created_by 字段。但是要发送到前端,我正在使用以下方法转换为 json: data = json.loads(serialize('json', cmets)) 这再次取回 created_by 字段中的 id
    • 您获得 id 是因为您直接从数据库序列化数据,而不是使用序列化程序。如果您不想使用序列化程序,请将您的查询集转换为 dict 并遍历它更改 dict 中的值,然后进行序列化。序列化器正是为此目的而制作的,请使用上面评论中的序列化器。
    猜你喜欢
    • 2015-04-20
    • 2019-01-03
    • 1970-01-01
    • 2010-12-14
    • 2019-01-02
    • 2019-01-17
    • 2014-04-21
    • 2016-08-23
    • 1970-01-01
    相关资源
    最近更新 更多