I have a model User and a model Thing. A User can own zero or more Things. A Thing may be owned by zero or more Users. Ordinarily I would add in a third table Thing_Ownership linking Users to Things but I would like to take advantage of SQLAlchemy’s backref feature so that if I had a User instance george I could call george.inventory to get a list of Things that belong to george.
What is the best way to go about this, or should I just add a third model and implement User.inventory as a search through a third Thing_Ownership model for relevant relationships?
Check out SQLAlchemy’s documentation on Many to Many relationships – it should do exactly what you’re looking for.
So if you have models for
UserandThing, you can set up a secondary parameter in your relationship:You can then access a list of
Things belonging to aUserinstantiated asgeorgeby callinggeorge.inventory.Hope this helps.
EDIT: Reread your question and saw you wanted to use
backref– added code to do that.EDIT 2: Left out a really important part.