如何在一个序列化器字段中表示GET和POST方法的不同值?

时间:2017-02-20 12:45:10

标签: django django-forms django-rest-framework

如何更改GET和POST请求的串行器表示? 目前我正在使用HotelSerializer中的StringRelatedField,它只允许readonly Feld我无法POST任何数据因为StringRelatedField没有在我的情况下用id映射但是id是manadotory对于POST请求。

如果我在HotelSerializer中使用PrimaryKeyRelatedField进行定位,则执行POST请求并成功保存对象

但点击api获取GET请求对于ID为1的酒店,响应将是

{ "id": 1, "name": "asasa", "discription": "sasas", "location": 1, } 

但是我希望响应应该包括城市名称,而不是我做GET请求时的位置ID

{ "id": 1, "name": "asasa", "discription": "sasas", "location": "delhi", }

{ "id": 1, "name": "asasa", "discription": "sasas","location": "Mumbai", } 

模型

class Location(models.Model):
    country =  models.CharField(max_length=60)
    city = models.CharField(max_length=60,db_index=True)
    zipcode = models.CharField(max_length=10
class Hotel(models.Model):
    name =models.CharField(max_length=200,db_index=True)
    discription = models.TextField(blank=True,null=True)
    location = models.ForeignKey(Location,related_name='hotels')

串行

class HotelSerializer(serializers.ModelSerializer):
    location=serializers.StringRelatedField() #this line Cause Problem

    class Meta:
        model = Hotel
        fields= ('id','name','discription','location',)

2 个答案:

答案 0 :(得分:2)

对于您的情况,您不需要任何特殊字段,DRF默认为您提供PrimaryKeyRelateField

class HotelSerializer(serializers.ModelSerializer):

    class Meta:
        model = Hotel
        fields= ('id','name','discription','location',)

默认情况下,Django中的所有字段都使用非空约束,例如null=False。如果要保存空值,则应在字段中明确写入:

class Hotel(models.Model):
    location = models.ForeignKey(Location,related_name='hotels', null=True, blank=True)

null=True允许您保存空值,并blank=True在表单验证中不需要此字段。
更新:
如果要更改序列化程序字段的表示形式,可以覆盖to_representation方法:

class HotelSerializer(serializers.ModelSerializer):

    class Meta:
        model = Hotel
        fields= ('id','name','discription','location')

    def to_representation(self, instance):
        representation = super(HotelSerializer, self).to_representation(instance)
        representation['location'] = instance.location.city
        return representation

答案 1 :(得分:1)

模型

location = models.ForeignKey(Location, null=True, blank=True)

串行

class HotelSerializer(serializers.ModelSerializer):
    location=serializers.PrimaryKeyRelatedField(queryset=Location.objects.all(), required=False) #this line Cause Problem

    class Meta:
        model = Hotel
        fields= ('id','name','discription','location',)