简体   繁体   English

在Django queryset中访问外键

[英]accessing foreign key in django queryset

In the example below, I have a model Proof which contains a foreign key to the model Option . 在下面的示例中,我有一个模型Proof ,其中包含模型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? 我将如何在Django中进行相关的联接? I tried using a _set.all() method but that doesn't seem to work on a queryset, only on a single listing. 我尝试使用_set.all()方法,但这似乎不适用于查询集,而仅适用于单个清单。

Thanks for your help :) 谢谢你的帮助 :)

Models.py 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 View.py

options = Option.objects.all()

I think this was supposed to work in template with options = Option.objects.all() in view(). 我认为这应该在view()中的options = Option.objects.all()模板中工作。

{% 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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