views:

56

answers:

2

Hi,

Can someone tell me, how I can access all contacts relating to a specific group? I'm new to Django and did this (according to the docs):

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 })

"groups" is for something different, I tried it with "group" and "contacts" but get a

'Group' object has no attribute 'contacts'

exception.

Here's the model I'm using

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

Thanks in advance!

EDIT: Oh and can someone tell me how I can add a contact to a group?

+3  A: 

You will need to modify your code as shown below:

contacts = group.contact_set.all()

See the relevant documentation for more details.

Manoj Govindan
nice. thank you!
Tronic
+1  A: 

One way:

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

Another, more idomatic, way:

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

contact_set is the default related_name for the relation as shown in the related objects docs.

If you wanted to, you could specify your own related_name, such as related_name='contacts' when defining the field and then you could do group.contacts.all()

To add a new Contact to a group, you just need to assign the relevant group to contact via the group field and save the Contact:

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() 

Sounds like you'd enjoy reading the free Django Book to get to grips with these fundamentals.

stevejalim
thank you so much!
Tronic