Reputation: 1348
I have a model Thing
which can be subclassed by several types of Thing
like PointyThing
and TastyThing
. I have a second model, Instance
that is related one-to-many to Thing
s (one Instance
may be of the type of a single Thing
but there will be many Instance
s of a given Thing
). Instance
s are then related to a Player
(each instance
has one Player
but a player
has many Instance
s) with a backref so that a Player
can call it's .inventory
property to see what it owns.
All well and good, but I also have a model Place
. I would like for Place
s to own Instance
s too in the same way that a Player
owns an instance
.
Would it be best to create an Owner
model that is linked against with the Instance
model and then subclassed to get Player
s and Place
s or some hereto unknown method within SQLAlchemy that I don't yet know of?
Upvotes: 3
Views: 328
Reputation: 77092
I think the best
solution you are asking for depends on many factors.
Technically, if I look at your example in isolation, this solution looks like a pretty descent hack
which avoids creating another relationship
table. And if you will never query with polymorphic support, this could fly just fine. However it would still be a hack. Imagine that later you extend your Player
model with few more sub-classes, and you might start using polymorphic queries, and you will always have to ask yourself "how will it impact my hack"?
. And even if everything still would work fine (right now I cannot come up with example which would break your logic), you would still need to be careful.
But lets look what is the benefit of this hack? We save on one relationship
table, but in fact you introduce another table for your Owner
model (I assume Concrete Table Inheritance), so what is the gain really?
On the other hand, I am wondering if your Instance
table should not in fact be a ternary
relationship? I assume that each instance of the Thing
is stored in some Place
and might belong to a Player
, so it might just be one table that looks like:
Instance[
ID primary_key,
Thing_ID (FK) NOT NULL,
Place_ID (FK) NOT NULL,
Person_ID (FK) NULL
]
Note that Person_ID
is nullable, as I assume the instance of the Thing might not belong to anyone until assigned. But it could be that it is always NOT NULL
in your case.
Hope this helps. Would be good to learn which way you decide to go and why.
Upvotes: 2