简体   繁体   中英

child model accesing the parent model feild in django

Hello guys I have one query in my Django project. I Have two models as mentioned below UserProfileInfo and Post. I want to bring profile_Pic in the Post model so that I can call in 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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