2021年4月28日星期三

How to display content from many-to-one relationship

So I'm going crazy trying to figure out what seems like it should be a dead-simple task.

I'm making a portfolio site. It has 2 models, Project and Image. Project contains most of the data for each project, while Image is in a many-to-one relationship to supply Project with a variable number of images per Project.

On the homepage, I would like to show each project in its own section, and the images for each project in their respective sections. Currently, I have the projects displayed, and I'm able to display all the images from the database under each section:

    

I cannot, for the life of me, figure out how to display just the images for each respective section in the template, despite diving through pages of documentation, stack answers, and web posts.

I've seen so many examples of how to query a model in this type of relationship from the views/model layers, but none of these seem to work in the template layer. I also don't know how I would perform the query on a different layer and send that through to the template, if I were to go that route.

models.py

class Project(models.Model):  title = models.TextField()  year = models.CharField(max_length=20)  tech = models.TextField()  role = models.TextField()  description = models.TextField()    def __str__(self):      return self.title    class Image(models.Model):  name = models.TextField()  image = models.ImageField(upload_to='images/project_images/')  project = models.ForeignKey(to=Project, on_delete=models.CASCADE)    def __str__(self):      return self.name  

views.py

def index(request):  home = Home.objects  projects = Project.objects  images = Image.objects    return render(request, 'portfolio/home.html', {'home': home,                  'projects': projects, 'images': images})  

template

    
https://stackoverflow.com/questions/67304906/how-to-display-content-from-many-to-one-relationship April 29, 2021 at 01:15AM

没有评论:

发表评论