我在MySQL中使用Django休息框架。
让我解释一下我的两张桌子。
[第]
- articleNo(主键)
- 内容
[注释]
- articleNo(FK to article)
- 用户密钥
- 评论
我想将评论数据导入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')
当我访问/文章时,当前输出是:
{
"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框架实现吗?
感谢。
答案 0 :(得分:0)
您需要在comment
内将PrimaryKeyField
字段的类型从commentSerializer
更改为articleDetailSerializer
:
class articleDetailSerializer(serializers.ModelSerializer):
...
comment = commentSerializer(many=True, read_only=True)
class Meta:
model = article
fields = ('articleNo', 'userkey', 'content', 'likeCount', 'commentCount', 'comment')
详见here。