在Django中获取和显示相关对象 [英] Getting and displaying related objects in Django
问题描述
我知道这很简单,但是我无法理解如何将某些模型结合在一起以显示在Django的模板中。我有可以有多个联系人的组。
I know this is simple, but I can't get my head around how to join some models together to display in my template in Django. I have "groups" that can have several "contacts".
到目前为止,我已经了解了:
So far I've got:
class Group(models.Model):
group_name = models.CharField()
class Contact(models.Model):
contact_name = models.ForeignKey(Group)
在我看来,起初我以为只是让我的组也可以获取任何附加的联系人,但是似乎未按预期发生:
In my view, at first I assumed that simply getting my groups would also get any attached contacts, however that doesn't appear to be happening as expected:
def get_queryset(self):
groups = Group.objects.all()
return groups
我原本希望这样做在我的模板中是这样的:
I was expecting to do something like this in my template:
{% for group in groups %}
<h2>{{ group.group_name }}</h2>
{% for c in group.contact %}
<h3>{{ c.contact_name }}</h3>
{% endfor %}
{% endfor %}
这是'无法正常工作-我在做什么错?在我看来,确保要检索每个组的联系人的正确查询是什么?
This isn't working - what am I doing wrong? What is the correct query in my view to make sure the contact(s) for each group is getting retrieved?
推荐答案
看起来您已经从其他地方获取了一些代码,因此为了完全理解,您可以通过 2种不同的方式进行操作:
Well, it looks like you've got some of your code from a different place so just so you can fully understand, you can do this in 2 different ways:
1)要访问任何类型的相关对象,只需简单的 ForeignKey
或 ManyToMany
,您只需要从相反的模型开始,使用set这样的例子:
1) To access a related object of any kind, being a simple ForeignKey
or ManyToMany
you just need to go from the opposite model and use _set like this example:
class Group(models.Model):
group_name = models.CharField()
class Contact(models.Model):
contact_name = models.ForeignKey(Group)
{{ group.contact_set.all }}
2)您可以设置不同于默认设置
的名称,更改联系人
像这样:
2) You can set up a name different than the default _set
changing Contact
like this:
class Contact(models.Model):
contact_name = models.ForeignKey(Group, related_name='contacts')
因此, related_name
kwarg为您设置一个新名称,而不是 set
一个:
So, related_name
kwarg set a new name for you instead of the _set
one:
{{ group.contacts.all }}
我希望我能可以更轻松地访问与模型相关的对象。
I hope I manage to make it clearer about simple access on models related objects.
这篇关于在Django中获取和显示相关对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!