2010-09-11 239 views
1

有人可以告訴我,我如何訪問與特定組相關的所有聯繫人?我是新來的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 

提前感謝的典範!

編輯:噢,有人可以告訴我如何添加聯繫人到一個組?

回答

5

一種方式:

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去與這些基本面交手。

+0

非常感謝你! – Tronic 2010-09-11 18:44:22

3

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

contacts = group.contact_set.all() 

詳情請參見相關documentation