Ok, not sure why I'm not getting replies, perhaps my problem is too 
complex or I'm being too silly with my approach. Either way, I found a 
work around by writing a little function to prepare my objects for 
saving which ensures that django finds the fkey id's when I issue my save():

def prepare_object(obj): # helper method to work around django 
restrictions of NULL foreign keys before saving
        for key in obj.__dict__:
                if key[0] == '_' or key[-3:] != '_id': # skip private 
and ordinary fields
                        continue
                fkey_name = key[:-3]
                try:
                        exec 'obj.%s = obj.%s.id' % (key, fkey_name)
                except:
                        pass # there are some normal attributes that end 
in _id but have got nothing to do with fkeys (hence don't have such 
attributes)

Perhaps it will spare another lone programmer a hair or two. If nobody 
has any further comments on this I think I'll just file a bug on 
django's trac, this issue really *shouldn't* be present.

Gunther.

gmayer wrote:
> Hi guys,
>
> I'm new to Django but otherwise quite a seasoned python and sql
> programmer. I'm baffled by django's foreign key id behaviour and as a
> result stuck in my current coding project. Let me start immediately
> with an example of what I'm trying to do. Assume two very simple
> models:
>
> class A(models.Model):
>     pass
> class B(models.Model):
>     a = models.ForeignKey(A)
>
> Now I need to create an instance of A and B without saving either of
> them (I'm parsing a whack load of data and only want to commit objects
> to the db once successfully parsed):
>
> from test.models import A,B
> instA = A()
> instB = B(a=instA)
>
> Now I'm done with my parsing and am happy to save them to my database:
>
> instA.save() # all good
> instB.save() # fails with IntegrityError: null value in column "a_id"
> violates not-null constraint
>
> On closer inspection the second line above fails because instB.a_id is
> None, even though instB.a.id is defined. Why does django throw in a
> duplicate, now stale instB.a_id field which, to make matters worse, is
> used in generating the underlying SQL for instB.save() to result in
> failure????
>
> Perhaps I'm just to n00b to use the correct semantics which avoid the
> above issues... excuse me if that's the case.
>
> Gunther
>   

--

You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.


Reply via email to