I want to use sqlalchemy in a way like this:
email1 = EmailModel(email="[email protected]", account=AccountModel(name="username"))
email2 = EmailModel(email="[email protected]", account=AccountModel(name="username"))
Usually sqlalchemy will create two entries for the account and link each email address to this. If i set the accountname as unique sqlalchemy is throwing an exception which tells me about an entry with the same value already exists. This makes all sense and works as expected.
Now i figured out an way by my own which allows the mentioned code and just creates an account only once by overwriting the the new Constructor of the AccountModel Class:
def __new__(*cls, **kw):
if len(kw) and "name" in kw:
x = session.query(cls.__class__).filter(cls[0].name==kw["name"]).first()
if x: return x
return object.__new__(*cls, **kw)
This is working perfectly for me. But the question is:
- Is this the correct way?
- Is there an sqlalchemy way of achieving the same?
I'm using the latest 0.8.x SQLAlchemy Version and Python 2.7.x
Thanks for any help :)