I'm just getting to grips with SQLObject so please pardon me if this is a question that has been asked before.
Is it possible to defer the insert/update so that the object can be validated before the changes are written to the database?
I would like to be able to do the following:
object = MyObject()
object.field1 = someValue
object.field2 = someValue
object.validate()
object.save()
With similar logic for objects that already exist in the database.
>From looking through the tutorial and source the philosophy seems to be to write all object changes to the database as they occur. This makes sense to me as it simplifies everything.
With this in mind I tried to create a wrapper class that collects updates and applies them to the object all at once, something like this:
class FormValues:
def __init__(self, clazz = None, object = None):
#clazz is set if we should create a new object, object is set if it's a pre-existing object
self.__clazz = clazz
self.__object = object
def __getattr__(self, attr):
if self.__dict__.has_key(attr):
return self.__dict__[attr]
else:
return None
def save(self):
if self.__object is None:
self.__object = self.__clazz()
for key in self.__dict__.keys():
if self.__object.__dict__.has_key(key):
self.__object.__dict__[key] = self.__dict__.[key]
The problem with this is that I'm not able to create the new object, because the self.__clazz() call requires keyword arguments for each field. I can get this to work by setting defaults for each column, but this seems an odd way to go about things and doesn't work very well for relations (and for tables with no auto increment field the ID is always 0, which causes a duplicate record error). Is there another way to create a new object?
I've also tried creating the object as follows:
self.__object = self.__clazz(_SO_fetch_no_create=1)
Which works initially but falls over as soon as it tries to write anything to the database because the object hasn't been initialised properly.
Am I going about this the wrong way? Is there a better way to acheive this?
Any comments would be greatly appreciated.
Peter Butler
|