[SQLObject] Patch for setdefault & replace constructors
SQLObject is a Python ORM.
Brought to you by:
ianbicking,
phd
From: Carlos R. <car...@gm...> - 2005-02-20 00:18:54
|
Hi all, Here follows a simple-minded patch for the setdefault & replace methods. It's pretty simple, and it helped to make my own code read a little less cluttered :-) 'setdefault' is useful to initialize a database with default objects. It ensures that the object exists, but allow customizations to be preserved. 'replace' writes the new values over the existing record, and thus preserves the same original id. It can be used to reset values to the default ones. Usage is as follows: # user contains the system users table. here we create the admin # account if it doesn't exist yet. It's just a sample, mind you... User.setdefault(testKey=3D'name', name=3D'admin', password=3D'admin') # this is similar to the test above, but the user account is overwriten # with the new definition User.replace(testKey=3D'name', name=3D'admin', password=3D'admin') I was in doubt whether to include the 'testKey' argument or not. Both methods could scan the table columns looking for some alternate key & the corresponding kw declaration. However, I thought that 'explicit is better than implicit' and put it as an additional argument, which helps to document the difference between these constructors and the standard one. p.s. There's no unit test, but I tested it inside my own system code and it worked. =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D --- sqlobject/main.py (revis=C3=A3o 619) +++ sqlobject/main.py (c=C3=B3pia de trabalho) @@ -1029,6 +1029,33 @@ self._create(id, **kw) + def setdefault(cls, testKey, **kw): + # If the object exists, return it; if it doesn't exist, create + # a new one and return. testKey is the name of the alternateKey + # to used for testing. Its value should be provided as a keyword + # argument. + dbTestKey =3D cls._SO_columnDict[testKey].dbName + try: + obj =3D cls._SO_fetchAlternateID(dbTestKey, kw[testKey], connection=3DNone) + except SQLObjectNotFound: + obj =3D cls(**kw) + return obj + + setdefault =3D classmethod(setdefault) + + def replace(cls, testKey, **kw): + # Overwrites an existing object with the values provided. If + # the object does not exist, create it. + dbTestKey =3D cls._SO_columnDict[testKey].dbName + try: + obj =3D cls._SO_fetchAlternateID(dbTestKey, kw[testKey], connection=3DNone) + obj.set(**kw) + except SQLObjectNotFound: + obj =3D cls(**kw) + return obj + + replace =3D classmethod(replace) + def _create(self, id, **kw): self._SO_creating =3D True --=20 Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: car...@gm... mail: car...@ya... |