如何使用Django Rest Framework序列化字符串列表

时间:2017-05-23 10:27:14

标签: django django-rest-framework

我在Django rest框架中有序列化程序如下:

class StateSerializer(serializers.ModelSerializer):       

    kilometers = Field(source='mileage')
    pictures = StatePictureSerializer(many=True, read_only=True)

    class Meta:
        model = Inspection   # Options
        fields = ('kilometers', 'inspection_date', 'pictures')

StatePictureSerializer如下:

class StatePictureSerializer(serializers.ModelSerializer):
    blob_url = Field(source='public_url')

    class Meta:
        model = Inspection_Picture
        fields = ('blob_url', )

结果我得到如下内容:

{    
    "kilometers": 64431, 
    "inspection_date": null, 
    "pictures": [
        {"blob_url": "path/to/photo"}, 
        {"blob_url": "path/to/photo"}, 
        {"blob_url": "path/to/photo"}, 
        {"blob_url": "path/to/photo"}, 
        {"blob_url": "path/to/photo"}
    ]
}

因此,pictures是一个对象数组。

我想要的是一个字符串数组,例如:

"pictures": ["path/to/photo", "path/to/photo", "path/to/photo", "path/to/photo", "path/to/photo"]

知道怎么做吗?

修改

Inspection模型如下:

class Inspection(models.Model):
    customerReference = models.CharField(max_length=50, blank=True, null=True)
    extraReference = models.CharField(max_length=50, blank=True, null=True)
    itemReference = models.IntegerField(blank=True, null=True)
    vehicle = models.ForeignKey(to=Vehicle)
    mileage = models.IntegerField()
    timeStamp = models.DateTimeField(auto_now_add=True)
    inspection_date = models.DateTimeField(null=True)
    features = models.ManyToManyField(to=Feature)
    pictures = models.ManyToManyField(to=Images, through="Inspection_Picture")
    damages = models.ManyToManyField(to=Damage)
    parts = models.ManyToManyField(to=Part)
    checks = models.ManyToManyField(to=CheckType, through=Inspection_Check)
    featuresFlat = models.ManyToManyField(to=FeatureFlat, through=Inspection_FeatureFlat)

Images模型如下:

class Images(models.Model):
    """Model for storing uploaded photos"""
    filename = models.CharField(max_length=255)
    extension = models.CharField(max_length=40)
    key_data = models.CharField(max_length=90, unique=True, blank=True, null=True)
    upload_date = models.DateTimeField(auto_now_add=True)
    upload_identification = models.CharField(max_length=50, blank=True, null=True)
    url = models.CharField(max_length=1024, blank=True, null=True)
    stored = models.BooleanField(default=False)
    thumbnailed = models.BooleanField(default=False)
    thumbnailed_treated = models.BooleanField(default=False)
    protected = models.BooleanField(default=False)
    source = models.CharField(max_length=50, blank=True, null=True)

    @property
    def key_generate(self):
        """returns a string based unique key with length 80 chars"""
        while 1:
            key = str(random.getrandbits(256))
            try:
                Images.objects.get(key=key)
            except:
                return key

    def __unicode__(self):
        return self.upload_identification

    def public_url(self):
        return settings.AZURE_URL_FULL + self.url

1 个答案:

答案 0 :(得分:5)

我认为在你的情况下SerializerMethodField将是一个正确的选择,如下所示。以下代码中可能存在<field_name>不匹配。请按照您的型号进行操作。我假设基于上面的序列化器的字段名称。

class StateSerializer(serializers.ModelSerializer):       

    kilometers = Field(source='mileage')
    pictures = serializers.SerializerMethodField('get_pictures')

    class Meta:
        model = Inspection   # Options
        fields = ('kilometers', 'inspection_date', 'pictures')

    def get_pictures(self, obj):
        return [each.public_url() for each in obj.pictures.all() ]