gpt4 book ai didi

python - Django 休息框架从另一个表导入数据?

转载 作者:行者123 更新时间:2023-11-30 21:47:44 26 4
gpt4 key购买 nike

我在 MySQL 中使用 Django 休息框架。

让我解释一下我的两个表。

[文章]
- 文章编号(主键)
- 内容

[评论]
- 文章编号(FK 到文章)
- 用户 key
- 评论

我想将评论数据导入artice表。

class articleDetailSerializer(serializers.ModelSerializer):
userkey = userSerializer(read_only=True)
likeCount = serializers.IntegerField(source='like_set.count', read_only=True)
commentCount = serializers.IntegerField(source='comment_set.count', read_only=True)
comment = serializers.PrimaryKeyRelatedField(many=True, read_only=True)

class Meta:
model = article
fields = ('articleNo', 'userkey', 'content', 'likeCount', 'commentCount', 'comment')

class commentSerializer(serializers.ModelSerializer):
class Meta:
model = comment
fields = ('articleNo', 'content', 'userkey')

当我访问/article 时,当前输出是:

{
"articleNo": 26,
"userkey": {
"userkey": "121212",
"username": "Da"
},
"content": "test",
"likeCount": 3,
"comment": [
1,
2,
3
]
},

我想要的输出是这样的:

{
"articleNo": 26,
"userkey": {
"userkey": "121212",
"username": "Da"
},
"content": "test",
"likeCount": 3,
"comment": [
{
articleNo: 26,
userkey: "12345",
content: "first comment"
},
{
articleNo: 26,
userkey: "23456",
content: "second comment"
},
{
articleNo: 26,
userkey: "33333",
content: "third comment"
},
]
},

可以用Rest框架实现吗?

谢谢。

最佳答案

您需要在 articleDetailSerializer 中将 comment 字段的类型从 PrimaryKeyField 更改为 commentSerializer:

class articleDetailSerializer(serializers.ModelSerializer):
...
comment = commentSerializer(many=True, read_only=True)

class Meta:
model = article
fields = ('articleNo', 'userkey', 'content', 'likeCount', 'commentCount', 'comment')

查看详情 here .

关于python - Django 休息框架从另一个表导入数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48680653/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com