1

I have two models

class Post(models.Model):
   ...

class PostImage(models.Model):
   post = models.ForeignKey(Post)
   ...

In a ListView I need to query a post and one image for it, so I end up writing a raw query. What I hit now is that the url fields are simple path strings which Django tries to load from my app, instead of the MEDIA_URL which otherwise works if the object is loaded via the ORM.

Is there a way to convert that path to the URL in the template using the Django syntax ?

{{ post.image.url }}
Ahmed Nour Eldeen
  • 351
  • 1
  • 4
  • 13
Zarrie
  • 325
  • 2
  • 16

1 Answers1

1

You can obtain the .first() [Django-doc] PostImage for example and use this to render the image URL:

{{ post.postimage_set.first.image.url }}

Here postimage_set is the default value for the related_name=… parameter [Django-doc], if you specify a related_name yourself, then you should replace postimage_set with that name.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • If I understand correctly each object of type Post has a refference to models with foreign key the given model which can be accessed using this field `related_name` ? – Zarrie Sep 20 '20 at 12:16
  • 1
    @Zarrie: not to an object, since a `ForeignKey` means that each `Post` can have *zero*, *one* or ***more*** `PostImage`s, the `related_name` is the name of a manager to access the related `PostImage`s of a `Post`. So `post.postimage_set` is a manager that manages the collection of related `PostImage` objects. You can for example use `.all()` to access all these objects, or `.first()` and `.last()` to access the first/last related object. – Willem Van Onsem Sep 20 '20 at 12:18