Reputation: 1022
I have a little problem which I can't seem to get my head around. It seems like a very trivial thing but I just can't figure it out. Essentially what I'm trying to do is to create a Project
model which holds information on a certain project and then have another model called Link
which holds the name of the link such as 'Get Program' or 'Download Release' and have a URLField which holds the URL for those links and is child of Project
.
So far my models.py
is as below:
from django.db import models
class Project(models.Model):
name = models.CharField(max_length=255)
description = models.TextField()
def get_name(self):
return self.name
def get_description(self):
return self.description
def __str__(self):
return self.name
class Link(models.Model):
project = models.ForeignKey(Project)
name = models.CharField(max_length=255)
url = models.URLField()
def get_name(self):
return self.name
def __str__(self):
return self.name
Problem is in my views.py
I want to be able to pass Projects object so I can iterate over them and display all links for each project including the project objects fields such as name and description. So far I've done:
from django.shortcuts import render
from django.http import HttpResponse
from .models import Project, Link
def projects_index(request):
projects = Project.objects.all()
links = Link.objects.all()
context = {
'projects': projects,
}
return render(request, 'projects.html', context)
Upvotes: 5
Views: 7974
Reputation: 228
You really should do the tutorial.
for project in projects:
for link in project.link_set.all:
<...>
Add a related_name="links"
to your foreign key, and the inner loop can be
for link in project.links:
Upvotes: 0
Reputation: 1717
Inside your template projects.html
you should be able to loop over the Links for each project with
{% for project in projects %}
{% for link in project.link_set.all %}
{{ link }}
{% endfor %}
{% endfor %}
Upvotes: 3