属性有 DB/ORM 模式吗?
我想创建一个具有不同键值作为属性的对象,例如:
animal
id
name
attribute
id
name
和映射,
animal_attribute
animal_id
attribute_id
这样我就可以有一个条目“鸭子”,它有多个属性“飞行”,“游泳”等。每个属性类型都有自己的属性表定义一些变量
attribute_flying
animal_id
height
length
..
attribute_swimming
animal_id
depth
..
有没有更好的方法来做到这一点?另外,对象布局在编程(python)中如何工作?
i want to create an object with different key-value as attributes, for example:
animal
id
name
attribute
id
name
and mapping
animal_attribute
animal_id
attribute_id
so i can have a entry "duck", which has multiple attribute "flying", "swimming", etc. Each attribute type would have its own table defining some variables
attribute_flying
animal_id
height
length
..
attribute_swimming
animal_id
depth
..
is there a better way to do this? Also how would the object layout work in programming (python)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您有多种选择。
如果您的对象层次结构不是很深并且只有几个属性,那么您可以创建一个表并为需要支持的每个属性添加列。
另一种方法是为每个对象创建表并将每个属性映射到不同的列。
由于以下问题,您想要使用的方法不是很好:
实际上,这就是所谓的实体-属性-值反模式,如 SQL Antipatterns 书中所述。
要解决此反模式,需要重新考虑如何在数据库中存储继承。有几种方法:
精确解决方案取决于您的任务,目前很难决定什么是最佳解决方案。可能您应该为每个子类使用表。在这种情况下,您将把公共属性存储在一个表中,而动物的所有特定属性都存储在附加表中。
sqlalchemy 支持所有三种主要类型的继承,请阅读 文档并选择最适合您需求的文档。
You have several alternatives.
If you have not very deep hierarchy of objects and just several attributes, then you can create one table and add columns for every attribute you need to support
Other way is to create table for each object and map each attribute to different column.
Approach you want to use is not very good due to the following issues:
Actually this is so called Entity-Attribute-Value antipattern, as described in SQL Antipatterns book.
To resolve this antipattern it is required to rethink how you will store your inheritance in database. There are several approaches:
Exact solution depends on your task, currently it is hard to decide what is the best solution. Possible you should use table per subclass. In this case you will store common attributes in one table and all specific for the animal goes to the additional table.
sqlalchemy supports all three major types of inheritance, read about inheritance configuration in the documentation and choose what is best for your needs.