Django中的多对一关系查询
问题描述:
有人可以告诉我,我如何访问与特定组相关的所有联系人?我是新来的Django,这样做,(根据文档):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
提前感谢的典范!
编辑:噢,有人可以告诉我如何添加联系人到一个组?
答
一种方式:
group = Group.objects.get(pk=group_id)
contacts_in_group = Contact.objects.filter(group=group)
另一个更idomatic,方式:
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去与这些基本面交手。
非常感谢你! – Tronic 2010-09-11 18:44:22