首页 > 解决方案 > 如何从 Profile 模型中获取图像到我的 Post 模型中

问题描述

我有两个模型ProfilePost. 我需要从Profile模型到Post模型访问图像。怎么做 ?

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image =  models.ImageField(upload_to='media')
    #Some other fields

class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    #Some other fields

标签: djangodjango-modelsdjango-viewsdjango-templates

解决方案


如果将Post要渲染的对象传递给上下文,则可以使用以下方式渲染帖子作者的图像post

<img src="{{ post.user.profile.image.url }}">

推荐阅读