Saving ManyToMany models

12 views
Skip to first unread message

LJ

unread,
Jun 21, 2012, 2:06:29 PM6/21/12
to django...@googlegroups.com
I am having trouble saving entities to my models that have ManyToMany relationships.
I have a Student object that inherits from a Person:

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    middle_name = models.CharField(max_length=30, blank=True)
    last_name = models.CharField(max_length=30)
    ...

class Student(Person):
    parents = models.ManyToManyField('parents.Parent', blank=True, null=True)
    ...

class Parent(Person):
    occupation = models.CharField(max_length=128, blank=True)

In my view, I create a new Student:

        newStudent = Student(first_name='Donald',
            middle_name='R', last_name='Duck')
        newStudent.save()

I also create a Parent and add the new parent to the list of parents for the student:

        newParent = Parent(first_name='Ronald',
            middle_name='T', last_name='Duck')
        newParent.save()
        newStudent.parents.add(newParent)

However, when I call save_m2m(), it throws an error:
        newStudent.save_m2m()

Perhaps I do not need to call save_m2m().  Does the relationship get saved to the database when I call the add() method?

LJ



Reply all
Reply to author
Forward
0 new messages