简体   繁体   中英

accessing foreign key in django queryset

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()

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 %}

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)

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