When I have models like this: class Foo(meta.Model) ... class Bar(meta.Model): foos = meta.ManyToManyField(Foo) class Baz(meta.Model) bar = meta.ForeignKey(Bar, edit_inline=True)
object creation will go something like this: obj = Bar(...) obj.save() # a must, or below code will complain about obj not having a ID obj.add_baz(some_function(),...) foos = some_other_function() obj.set_foos(foos) OK so far, but: obj = Bar(...) obj.save() obj.add_baz(some_function(),...) foos = some_other_function() # AND THIS THROWS A EXCEPTION obj.set_foos(foos) Then I have obj, with some of baz objects added but no Foo's!! Currently I have to write something like this: obj = Bar(...) obj.save() try: obj.add_baz(some_function(),...) except: obj.delete() raise try: foos = some_other_function() obj.set_foos(foos) except: # find and delete related baz objects obj.delete() Wow, it's just like Java ;) IMHO we have two solutions here, use transactions (and probably easier to implement) like this: BEGIN TRANSACTION; try: obj = Bar(...) obj.save() # a must! obj.add_baz(some_function(),...) foos = some_other_function() obj.set_foos(foos) COMMIT; except: ROLLBACK; Or something like this which is to me more logical and pythonic: try: obj = Bar(...) obj.add_baz(some_function(),...) foos = some_other_function() obj.set_foos(foos) obj.save() # this will save obj and then save all baz and foo objects except: # try to recover from error, report, do something! :) What I want here is that I don't need to call .save() (and store object data in database) before adding M2M and related FK data. Or there is a another solution for this? --- Nebojša Đorđević - nesh Studio Quattro - Niš - SCG http://studioquattro.biz/ http://djnesh.blogspot.com/ | http://djnesh-django.blogspot.com/ | http://djangoutils.python-hosting.com/ Registered Linux User 282159 [http://counter.li.org]
PGP.sig
Description: This is a digitally signed message part