ManyToMany relationship can't be saved

97 views
Skip to first unread message

Adam Smith

unread,
Nov 22, 2013, 12:31:38 AM11/22/13
to django-d...@googlegroups.com
As I was learning the Django Docs (https://docs.djangoproject.com/en/1.6/topics/db/models/#extra-fields-on-many-to-many-relationships), I found the following code not working. Is it a bug? At least the result is unexpected.

ringo = Person(name="Ringo")
beatles = Group(name="Beatles")
m1 = Membership(person=ringo, group=beatles,
                date_joined=date.today(),
                reason='whatever')
ringo.save(), beatles.save()
print m1.person.id, m1.group.id  # yes, they have values.
m1.save()  # IntegrityError: membership.person_id may not be NULL

Why can't m1 be save, since both its foreign key fields have been save successfully?

Thanks.
 

Curtis Maloney

unread,
Nov 22, 2013, 12:40:29 AM11/22/13
to django-d...@googlegroups.com
At first glance, I'd guess it's because the PK for ringo and beatles haven't been updated in the instances you have.


--
You received this message because you are subscribed to the Google Groups "Django developers" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-develop...@googlegroups.com.
To post to this group, send email to django-d...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-developers.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-developers/1d4d456f-abff-48fe-bf4c-0014c50abe9c%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Shai Berger

unread,
Nov 25, 2013, 5:27:35 AM11/25/13
to django-d...@googlegroups.com
m1 actually has more "fields" than meet the eye: besides person and group,
there are also person_id and group_id (and these are the attributes that go
into the database). The *_id attributes are set when the object attributes are
set -- that is, the assignment

m1.person = ringo # implicit in your code, executed by the initializer

causes also

m1.person_id = ringo.id

In your sample, this was done before ringo and beatles were saved, so the id
value was still None.

A case can be made for updating the ids for FK fields before saving an object,
which will make your problem go away. Off hand, I'm -0 on that -- it reeks of
"action at a distance", on pure instinct I'd say it will probably cause more
problems than it solves.

Shai.
Reply all
Reply to author
Forward
0 new messages