Django中的多对一关系查询

Tro*_*nic 1 python django orm exception 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 })
Run Code Online (Sandbox Code Playgroud)

"群体"用于不同的东西,我用"群组"和"联系人"尝试了但是得到了一个

'Group' object has no attribute 'contacts'
Run Code Online (Sandbox Code Playgroud)

例外.

这是我正在使用的模型

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
Run Code Online (Sandbox Code Playgroud)

提前致谢!

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

Ste*_*lim 5

单程:

group = Group.objects.get(pk=group_id)
contacts_in_group = Contact.objects.filter(group=group)
Run Code Online (Sandbox Code Playgroud)

另一种更加自律的方式:

group = Group.objects.get(pk=group_id)
contacts_in_group = group.contact_set.all() 
Run Code Online (Sandbox Code Playgroud)

contact_setrelated_name关系的默认值,如相关对象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() 
Run Code Online (Sandbox Code Playgroud)

听起来你喜欢阅读免费的Django Book来掌握这些基础知识.