简体   繁体   English

Django restframework从另一个表导入数据?

[英]Django restframework import data from another table?

I'm using Django rest framework with MySQL. 我将Django rest框架与MySQL结合使用。

Let me explain my two tables. 让我解释一下我的两张桌子。

[article] [文章]
- articleNo(Primary key) -articleNo(主键)
- content -内容

[comment] [评论]
- articleNo(FK to article) -articleNo(从FK到article)
- userkey - 用户密钥
- comment -评论

I want to import comment data to artice table. 我想将评论数据导入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')

When I visit /article, Current output is: 当我访问/ article时,当前输出为:

{
    "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? 可以用Rest框架实现吗?

Thanks. 谢谢。

You need to change type of comment field from PrimaryKeyField to commentSerializer inside articleDetailSerializer : 您需要在commentSerializer内将comment字段的类型从PrimaryKeyField更改为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 . 在这里查看详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM