Search code examples
djangodjango-rest-frameworkresponsedispatchserialization

Add additional fields data in response to post method in Django


I need to show additional field data for the POST response. This additional field data is not inserting or updating into the database, just want to get in response. this additional data is getting from another model. I need to customize the response JSON representation

model

class Country(BaseModel):
    name= models.CharField(null=True)
    state= models.FloatField(null=True)
    class Meta:
        db_table = 'country'
class Tour(BaseModel):
    name = models.ForeignKey(Country, on_delete=models.PROTECT)
    country= models.FloatField(null=True)
    class Meta:
        db_table = 'tour'   


class TourInter(BaseModel):
    tour = models.ForeignKey(Tour, on_delete=models.PROTECT)
    price= models.FloatField(null=True)
    details= models.TextField(null=True, blank=True)
    class Meta:
        db_table = 'tourinternational'

Serializer.py

class TourInterCreateSerializer(serializers.ModelSerializer):
    country = serializers.CharField(required=False,read_only=True)


    class Meta:
        model=TourInter
        fields = ('id','tour','price','country')    
    def validate(self, attrs):
        tour_id=attrs.get('tour').id
        tourintid = TourInter.objects.filter(tour=tour_id)[0].id
        countryobj = Tour.objects.get(id=tourid).country
        country = countryobj.state
        attrs.pop({'country': country})
        attrs = super().validate(attrs)
        return attrs

views.py

class TourInterViewSet(viewsets.ModelViewSet):
    queryset = TourInter.objects.all()
    def get_serializer_class(self):
        if self.action == 'create' or self.action == 'update':
            return TourInterCreateSerializer
        return TourInterSerializer

    def dispatch(self,request,*args,**kwargs):
        response = super(TourInterViewSet, self).dispatch(request, *args, **kwargs)
        data = {}
        data= response.data
        response.data = data
        return response

postman data

request:

{
tour_id: 1,
price: 10000
details: "Could be nil"
}

I need a postman response like a below-having country name for post response, here country is not inserting into the database:

{
tour_id: 1,
price: 10000
details: "Could be nil",
country: "Country name from country model"#this field should be added in response
}

Solution

  • Update serializer like this

    class TourInterCreateSerializer(serializers.ModelSerializer):
        country = serializers.SerializerMethodField()
    
        def get_country(self, instance):
            # Get country from country model
            return 'abc' # Write your own logic here
    
        class Meta:
            model=TripVisa
            fields = ('id','tour','price','country')    
        def validate(self, attrs):
            tour_id=attrs.get('tour').id
            tourintid = TourInter.objects.filter(tour=tour_id)[0].id
            countryobj = Tour.objects.get(id=tourid).country
            country = countryobj.state
            attrs.pop({'country': country})
            attrs = super().validate(attrs)
            return attrs