如何使用基于 SQLAlchemy 中角色的判别器正确建模连接表继承
是否可以指定另一个表中的鉴别器列?我如何使用声明式来做到这一点?
原因是我有一个连接表继承,
class User(Base):
id = Column(...)
class Customer(User):
customer_id = Column('id', ...)
class Mechanic(User):
mechanic_id = Column('id', ...)
class Role(Base):
id = Column(..)
但想通过用户拥有的角色来区分。用户可以具有买方角色或卖方角色或两者兼而有之。
这是模拟这种情况的正确方法吗?
请注意,还有买方特定数据和卖方特定数据,这就是我使用连接表继承的原因。
Is it possible to specify a discriminator column from another table? How do I do this with Declarative?
The reason for this is I have a joined table inheritance with
class User(Base):
id = Column(...)
class Customer(User):
customer_id = Column('id', ...)
class Mechanic(User):
mechanic_id = Column('id', ...)
class Role(Base):
id = Column(..)
but want to discriminate by Roles a user has. A user could have a buyer role or a seller role or both.
Is this the correct way to model this scenario?
As a note, there is Buyer specific data and Seller specific data as well, and that is why I am using the joined table inheritance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一种实现特定结果的笨拙且低效的方法,如果目标用户上存在多个角色,该方法也会失败:
接下来,如果我遇到基于零分配行为的问题,那么我实际上会这样做或更多角色 - 我会将行为放在角色中,而不是角色的所有者中:
第二个示例产生输出:
如您所见,第二个示例清晰且高效,而第一个示例只是一个思想实验。
Here's an awkward and inefficient way to achieve the specific result, which will also fail if more than one Role is present on the target User:
Next, here is how I would actually do it, if I had the issue of assigning behaviors based on zero or more Roles - I'd put the behavior in the Role, not the owner of the Role:
The second example produces the output:
As you can see the second example is clear and efficient while the first is just a thought experiment.
在最一般的情况下,我会说“不”。
在最一般的情况下,“买家”和“卖家”这两个词并不描述角色。它们描述了两方之间的关系。 (两个人之间、两个公司之间或个人与公司之间。)这种关系取决于一方至少从另一方购买一件东西。
您可能需要买家和卖家表(带有用户表的外键)来记录仅与买家或卖家相关的详细信息。但在没有任何此类详细信息的情况下,销售表(例如 {buyer_id, seller_id, Product, date_time})将是记录谁从谁那里购买了什么商品的“正常”方式。
In the most general case, I'd say "No".
In the most general case, the words buyer and seller don't describe roles. They describe a relationship between two parties. (Between two individuals, between two companies, or between an individual and a company.) The relationship depends on one party buying at least one thing from the other party.
You might need tables of buyers and sellers (with foreign keys to the users table) to record details related only to the buyer or only to the seller. But in the absence of any such details, a table of sales, like {buyer_id, seller_id, product, date_time}, would be the "normal" way to record who bought what from whom.