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
class Post(AbstractBaseModel):
creator_id = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="post_creator_id")
goal_id = models.ForeignKey(Goal, on_delete=models.CASCADE)
body = models.CharField(max_length=511, validators=[MinLengthValidator(5)])
hash_tags = models.ManyToManyField(HashTag)
class Photo(AbstractBaseModel):
created = models.DateTimeField('Created at', auto_now_add=True)
post_id = models.ForeignKey(Post, on_delete=models.CASCADE)
image = models.ImageField(upload_to=directory_path)
view.py
def get(self, request):
data = Post.objects.order_by('created').values('body', 'goal_id__description', 'created',
'creator_id__username', replies=Count('replypost'),
cheers=Count('cheerpost'), image_urls='photo__image_url')
return Response(list(data), status=status.HTTP_200_OK)