Skip to content
Advertisement

Django – Get urls of all images that reference a Post?

I have this model where a Post can have many Photos. I’m trying to retrieve all posts, including ImageField url attribute (according to Django docs FileField and ImageField have a url attribute). So I’d like to ideally return all the urls of the images associated with the post (ideally in order of created).

model.py

JavaScript

view.py

JavaScript

Advertisement

Answer

Please do not use .values(…) [Django-doc] to perform JSON serialization. This will errode the logical layer of a model, and for related objects it will act as a multiplier: per related Photo the body, etc. will be repeated.

We can define a function to retrieve the image URL of a Photo with:

JavaScript

You can work with a serializers that determine how to return objects. For the Photo, we can work with a PhotoSerializer:

JavaScript

Then we can serialize and return the coressponding serialized data with:

JavaScript
Advertisement