0

I have serializer in Django rest framework as follows:

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')

And StatePictureSerializer is as follows:

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

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

As result I get something as follows:

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

Thus, pictures is an array of objects.

What I want is an array of strings, for example:

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

Any idea how to do that?

EDIT

Inspection model is as follows:

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)

And Images model is as follows:

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 Answer 1

5

I think in your case SerializerMethodField would be a right choice as follows. There may be <field_name> mismatch in the code below. Please make it working according your model. I assume the field names based on your serializer above.

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() ]
Sign up to request clarification or add additional context in comments.

2 Comments

I get 'ManyRelatedManager' object is not iterable error. I updated my question with those two models.
Please change the method return to : ``` return [each.public_url() for each in obj.pictures.all() ] ```. It should fix the issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.