Re: [Modeling-users] Foreign Keys
Status: Abandoned
Brought to you by:
sbigaret
|
From: Sebastien B. <sbi...@us...> - 2003-07-21 15:41:53
|
Yannick Gingras <yan...@sa...> wrote:
> On July 21, 2003 10:09 am, Yannick Gingras wrote:
> > Hi, I'd like to set my foreign keys by hand ex.:
> >
> > i18n =3D I18N()
> > ec.insert(i18n)
> > i18n.setMasterId(masterSnapshot["id"])
> > ec.saveChanges()
> >
> > Is there a way to do it without breaking anything ?
>=20
> Of course there is a way, just set the foreign key to be class property.
>=20
> Forgive me to post before proper re-caffeination !
Oh oh, here you can get into very serious troubles. Demonstration, using
test package AuthorBooks where I made Book's FK_Writer_Id a class
property:
>>> from AuthorBooks.Book import Book
>>> from Modeling.EditingContext import EditingContext
>>> ec=3DEditingContext()
>>> rabelais=3Dec.fetch('Writer', 'lastName=3D=3D"Rabelais"', rawRows=3D1)[=
0]
>>> b=3DBook()
>>> b.setTitle('test')
>>> ec.insert(b)
>>> b.setFK_Writer_Id(rabelais['id'])
>>> print b.getAuthor()
None
>>> b.getFK_Writer_Id()
2
>>> ec.saveChanges()
>>> print b.getAuthor() # still None
>>> b.getFK_Writer_Id() # but fk is set
2
>>> # fetching doesn't help
... print ec.fetch('Book', 'title=3D=3D"test"')[0].getAuthor()
None
>>> # and fetching the other objects does not help either
... # because the fk_writer_id field in database is NULL!!
... books=3Dec.fetch('Writer', 'lastName=3D=3D"Rabelais"')[0].getBooks()
>>> print [b.getTitle() for b in books]
['Gargantua']
Worse: if you look at your database, you'll see that the fk_writer_id is
NULL!!
Any fetch w/ a different EC will give you a different view:
>>> ec2=3DEditingContext()
>>> print ec2.fetch('Book', 'title=3D=3D"test"')[0].getAuthor()
None
>>> print ec2.fetch('Book', 'title=3D=3D"test"')[0].getFK_Writer_Id()
None
What happened here? The FK is automatically set by the framework, by
examining the relationships. Since no object is related to book for
relation 'author', the FK gets overriden w/ the None value.
That's an illustration of why PKs and FKs should be considered
*read-only* when they are made class properties, as stated in the faq
[http://modeling.sf.net/UserGuide/faq-change-class-location.html].
Note: this is only one of the numerous problems you can get, including
inconsistencies in the graph of objects, changes not being saved,
etc., when doing this. The fact is that setting a PK or a FK is not
supported, not even expected, by the framework, and should not be done
under any circumstances.
-- S=E9bastien.
BTW: I noticed while "playing" with this that FKs that are class
properties do not get their values updated after saveChanges().
This is a bug that will be fixed.
|