Django Rest Serializers: Return data of related field

时间:2017-11-13 06:21:26

标签: django django-rest-framework

I created models which are Contracts and ContractItems. ContractItems table contains a foreign key attribute of Contracts table. I need to return Contracts with their relevant ContractItems.

I implemented a serializer like it.

class ContractSerializer(ModelSerializer):
    class Meta:
        model = Contract
        fields = ('id', 'name')

I could not get ContractItems to relevant Contract.

Could anyone suggest any way to get Contracts with their relevant ContractItems? And also One Contract can have many ContractItems.

2 个答案:

答案 0 :(得分:3)

class ContractItemSerializer(ModelSerializer):
    class Meta:
        model = ContractItems
        fields = '__all__'  

class ContractSerializer(ModelSerializer):

    contract_items  =  serializers.SerializerMethodField()
    class Meta:
        model = Contract
        fields = ('id', 'name')

    def get_contract_items(self, obj):
        qs = obj.related_name.all()
        return  ContractItemSerializer(qs, many=True).data

答案 1 :(得分:1)

也许你也试试这个。您也可以序列化相关对象。

class ContractItemSerializer(ModelSerializer):
    class Meta:
        model = ContractItems
        exclude = ()
class ContractSerializer(ModelSerializer):
    contract_items  =  ContractItemSerializer(many=True, read_only=True)    
    class Meta:
        model = Contract
        fields = ('id', 'name')

选中此项以供参考:Example