On Friday 22 November 2013 07:31:38 Adam Smith wrote:
> As I was learning the Django Docs (
> https://docs.djangoproject.com/en/1.6/topics/db/models/#extra-fields-on-man
> y-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?
>
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.
--
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 [email protected].
To post to this group, send email to [email protected].
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/201311251227.35936.shai%40platonix.com.
For more options, visit https://groups.google.com/groups/opt_out.