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

添加其他字段数据以响应Django中的post方法,django,django-rest-framework,response,dispatch,serialization,Django,Django Rest Framework,Response,Dispatch,Serialization,我需要为POST响应显示其他字段数据。此附加字段数据没有插入或更新到数据库中,只是希望得到响应。此附加数据来自另一个模型。我需要定制响应JSON表示 模型 序列化程序.py views.py 邮递员数据 请求: { tour_id: 1, price: 10000 details: "Could be nil" } 我需要一个邮递员的回复,比如下面有一个国家的名字 回复后,此处国家/地区未插入数据库: { tour_id: 1, price: 10000 details: "Could be

我需要为POST响应显示其他字段数据。此附加字段数据没有插入或更新到数据库中,只是希望得到响应。此附加数据来自另一个模型。我需要定制响应JSON表示

模型 序列化程序.py views.py 邮递员数据 请求:

{
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
}

像这样更新序列化程序

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

我如何从post方法中获取tour\u id,在验证中,我们有attrs,并且可以像tour\u id=attrs一样获取。获取(“tour\u id”)您的数据将在
self中可用。在post/put的情况下,初始\u数据
。tour\u id=instance.tour.id是获取参数的方法。Si正在谈论发布的数据。我对上面的代码进行了评论,以帮助其他人来到这里
{
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
}
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