简体   繁体   English

子 model 访问父 model 字段在 django

[英]child model accesing the parent model feild in django

Hello guys I have one query in my Django project.大家好,我的 Django 项目中有一个查询。 I Have two models as mentioned below UserProfileInfo and Post.我有两个模型,如下所述 UserProfileInfo 和 Post。 I want to bring profile_Pic in the Post model so that I can call in HTML.我想在帖子 model 中带来 profile_Pic,以便我可以调用 HTML。

class UserProfileInfo(models.Model):
    user = models.OneToOneField(
        User, on_delete=models.CASCADE, related_name='users1')
    portfolio_site = models.URLField(blank=True)
    bio = models.CharField(max_length=2000)
        profile_pic = models.ImageField(upload_to='profile_pics', blank=True)
    def __str__(self):
      

class Post(models.Model):
  )
    author = models.ForeignKey(
        UserProfileInfo, related_name='users', on_delete=models.CASCADE)
    
    title = models.CharField(max_length=200)
    text = models.CharField(max_length=2000)
    create_date = models.DateTimeField(default=timezone.now())
    published_date = models.DateTimeField(blank=True, null=True)

    def __str__(self):
        return self.title

You can access the related UserProfileInfo model instance and it's field by following the author ForeignKey您可以按照author ForeignKey访问相关的UserProfileInfo model 实例及其字段

post = Post.objects.get()
profile_pic = post.author.profile_pic
profile_pic_url = post.author.profile_pic.url  # For use in your template

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM