Django中的多对一关系查询

时间:2010-09-11 11:33:17

标签: python django exception orm foreign-key-relationship

有人可以告诉我,我如何访问与特定群组相关的所有联系人?我是Django的新手并且这样做了(根据文档):

def view_group(request, group_id):
    groups = Group.objects.all()
    group = Group.objects.get(pk=group_id)
    contacts = group.contacts.all()
    return render_to_response('manage/view_group.html', { 'groups' : groups, 'group' : group, 'contacts' : contacts })

“群组”用于不同的东西,我用“群组”和“联系人”尝试了但是得到了

'Group' object has no attribute 'contacts'

异常。

这是我正在使用的模型

from django.db import models

# Create your models here.

class Group(models.Model):
    name = models.CharField(max_length=255)
    def __unicode__(self):
            return self.name

class Contact(models.Model):
    group = models.ForeignKey(Group)
    forname = models.CharField(max_length=255)
    surname = models.CharField(max_length=255)
    company = models.CharField(max_length=255)
    address = models.CharField(max_length=255)
    zip = models.CharField(max_length=255)
    city = models.CharField(max_length=255)
    tel = models.CharField(max_length=255)
    fax = models.CharField(max_length=255)
    email = models.CharField(max_length=255)
    url = models.CharField(max_length=255)
    salutation = models.CharField(max_length=255)
    title = models.CharField(max_length=255)
    note = models.TextField()
    def __unicode__(self):
            return self.surname

提前致谢!

编辑:哦,有人可以告诉我如何将联系人添加到群组中吗?

2 个答案:

答案 0 :(得分:5)

一种方式:

group = Group.objects.get(pk=group_id)
contacts_in_group = Contact.objects.filter(group=group)

另一种更加自律的方式:

group = Group.objects.get(pk=group_id)
contacts_in_group = group.contact_set.all() 

contact_set是关系的默认related_name,如related objects docs所示。

如果您愿意,可以在定义字段时指定自己的related_name,例如related_name='contacts',然后您可以group.contacts.all()

要向群组添加新联系人,您只需要通过群组字段指定要联系的相关群组并保存联系人:

the_group = Group.objects.get(pk=the_group_id)
newcontact = Contact()
...fill in various details of your Contact here...
newcontact.group = the_group
newcontact.save() 

听起来你喜欢阅读免费的Django Book来掌握这些基本原理。

答案 1 :(得分:3)

您需要修改代码,如下所示:

contacts = group.contact_set.all()

有关详细信息,请参阅相关的documentation