添加其他字段数据以响应Django中的post方法

问题描述 投票:0回答:1

我需要显示POST响应的其他字段数据。这个附加字段数据不是要插入或更新到数据库中,而只是想获得响应。这些额外的数据是从另一个模型获得的。我需要自定义响应JSON表示形式

型号

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

邮递员数据

请求:

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

我需要一个邮递员回复,例如以下国家/地区名称发布回复,此处国家/地区未插入数据库:

{
tour_id: 1,
price: 10000
details: "Could be nil",
country: "Country name from country model"#this field should be added in response
}
django django-rest-framework response dispatch serializer
1个回答
0
投票

更新这样的序列化器

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
© www.soinside.com 2019 - 2024. All rights reserved.