On Sunday 07 February 2010 04:07:22 Luc Saffre wrote: > Luke, I disagree with your explanations. Django behaves oddly. > > Model.save() is the place where empty non-nullable fields cause an > exception. > There is no reason for ForeignKey to behave differently. > ForeignKey fields are different in that they cause database lookups > when they are not None, and that they can cause exceptions in some > special situations, for example > - asking them to save before the foreign instance has been saved > - database integrity errors (invalid non-None pk) > > That said, it is clear that I don't know Django well enough to > decide whether it is feasible/necessary to fix this odd behaviour.
It is easy to fix - a few lines in ReverseSingleRelatedObjectDescriptor - because the behaviour there is not accidental, but quite deliberate. The behaviour is only odd from one angle, and it is not very strange, because ForeignKey fields *are* a fundamentally different type of field. The corresponding 'normal' field is the '_id' field - this is a dumb value. I think you are missing the fact that this behaviour occurs *whenever* the FK val is an invalid value, not just with creating new instances. You are therefore asking either for special treatment of instances that are not saved to the database, or for it to be broken in general. Consider this code: >>> o = SomeModel.objects.get(id=1) >>> o.fk_field_id = None >>> print o.fk_field Are you are proposing that the above should print 'None' even when fk_field is non-nullable, rather than a DoesNotExist? 'o.fk_field' is a shortcut for a DB lookup of 'o.fk_field_id', and clearly the result of that lookup is *not* None/NULL. The query returns no results, and, just like every other case when a query returns no results and we expect at least one, you get a DoesNotExist exception. (In this case we skip doing the actual database query as an optimisation, but the same logic applies). Luke -- "Yes, wearily I sit here, pain and misery my only companions. And vast intelligence of course. And infinite sorrow. And..." (Marvin the paranoid android) Luke Plant || http://lukeplant.me.uk/ -- You received this message because you are subscribed to the Google Groups "Django developers" group. To post to this group, send email to django-develop...@googlegroups.com. To unsubscribe from this group, send email to django-developers+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-developers?hl=en.