I'm using Django rest framework with MySQL.
Let me explain my two tables.
[article]
- articleNo(Primary key)
- content
[comment]
- articleNo(FK to article)
- userkey
- comment
I want to import comment data to artice table.
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')
When I visit /article, Current output is:
{
"articleNo": 26,
"userkey": {
"userkey": "121212",
"username": "Da"
},
"content": "test",
"likeCount": 3,
"comment": [
1,
2,
3
]
},
What I would like instead as output is something like:
{
"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"
},
]
},
Can it be implemented with Rest framework?
Thanks.
You need to change type of comment
field from PrimaryKeyField
to commentSerializer
inside articleDetailSerializer
:
class articleDetailSerializer(serializers.ModelSerializer):
...
comment = commentSerializer(many=True, read_only=True)
class Meta:
model = article
fields = ('articleNo', 'userkey', 'content', 'likeCount', 'commentCount', 'comment')
See details here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.