user7185835
user7185835

Reputation:

Django Rest Serializers: Return data of related field

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.

Upvotes: 1

Views: 1221

Answers (2)

rajkris
rajkris

Reputation: 1793

Maybe you try this too. You can get the related objects serialized too.

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')

Check this for reference: Example

Upvotes: 1

Nakul Narayanan
Nakul Narayanan

Reputation: 1452

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

Upvotes: 3

Related Questions