Reputation: 3060
In the example below, I have a model Proof
which contains a foreign key to the model Option
.
I want to list all the options in my template along with their respective proofs. How would I go about making the relevant joins in django? I tried using a _set.all()
method but that doesn't seem to work on a queryset, only on a single listing.
Thanks for your help :)
Models.py
class Option(TimeStampActivate):
title = models.CharField(max_length=500,null=True)
user = models.ForeignKey(User)
option = models.CharField(max_length=300)
class Proof(TimeStampActivate):
user = models.ForeignKey(User)
option = models.ForeignKey(Option)
comment = models.CharField(max_length=500,null=True)
link = models.URLField()
View.py
options = Option.objects.all()
Upvotes: 0
Views: 1245
Reputation: 1196
I think this was supposed to work in template with options = Option.objects.all()
in view().
{% for option in options %}
{{option}}
{% for proof in option.proof_set.all %}
{{proof}}
{% endfor %}
{% endfor %}
Upvotes: 4
Reputation: 43832
There is probably a fancy way to query and get what you want, but how about creating a dictionary of the proofs keyed by the option?
from collections import defaultdict
proofs = Proof.objects.all()
options = defaultdict(list)
for p in proofs:
options[p.option].append(p)
Upvotes: 0