在django rest框架序列化器中,如何将主键表的数据与主表一起返回?

时间:2016-04-05 16:23:57

标签: django django-rest-framework

我有发布模型和标识符模型。两者都是相关的,因为post的PK是标识符的FK。从post表返回数据时,我还需要返回标识符表数据。我怎样才能有效地做到这一点?

models.py

class SharedIdentifier(models.Model):
    post = models.ForeignKey('post.Post',related_name='ref_posts', on_delete=models.CASCADE)
    label = models.CharField(max_length=32)
    value = models.CharField(max_length=50)

serializers.py

class SharedIdentifierSerializer(serializers.ModelSerializer):

    class Meta:
        model = SharedIdentifier
        fields = ('id', 'post', 'label', 'value',)
        read_only_fields = ('post')

class PostSerializer(serializers.ModelSerializer):
    author = UserSerializer(required=False,)
    ref_user = UserSerializer(read_only=True)
    ref_user_id = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(), write_only=True, source='ref_user')

    identifier = serializers.CharField(max_length=32, write_only=True)
    identifier_info = SharedIdentifierSerializer(required=False,many=True,read_only=True)

    class Meta:
        model = Post
        fields = ('id', 'author', 'ref_user', 'ref_user_id', 'status', 'message', 'type', 'parent_id', 'rating', 'create_date', 'close_date','identifier','identifier_info',)
        read_only_fields = ('status', 'close_date', 'author', 'ref_user','identifier_info',

1 个答案:

答案 0 :(得分:1)

Post模型的序列化程序上使用nested relationship,它指向Identifier模型的序列化程序。