This source details how to use association proxies to create views and objects with values of an ORM object.
However, when I append an value that matches an existing object in the database (and said value is either unique or a primary key), it creates a conflicting object so I cannot commit.
So in my case is this only useful as a view, and I’ll need to use ORM queries to retrieve the object to be appended.
Is this my only option or can I use merge (I may only be able to do this if it’s a primary key and not a unique constraint), OR set up the constructor such that it will use an existing object in the database if it exists instead of creating a new object?
For example from the docs:
user.keywords.append('cheese inspector')
# Is translated by the association proxy into the operation:
user.kw.append(Keyword('cheese inspector'))
But I’d like to to be translated to something more like: (of course the query could fail).
keyword = session.query(Keyword).filter(Keyword.keyword == 'cheese inspector').one()
user.kw.append(keyword)
OR ideally
user.kw.append(Keyword('cheese inspector'))
session.merge() # retrieves identical object from the database, or keeps new one
session.commit() # success!
I suppose this may not even be a good idea, but it could be in certain use cases 🙂
The example shown on the documentation page you link to is a
compositiontype of relationship (in OOP terms) and as such represents theownstype of relationship rather thenusesin terms of verbs. Therefore eachownerwould have its own copy of the same (in terms of value) keyword.In fact, you can use exactly the suggestion from the documentation you link to in your question to create a custom
creatormethod and hack it to reuse existing object for given key instead of just creating a new one. In this case the sample code of theUserclass andcreatorfunction will look like below: