通过 SQLAlchemy 实现多表映射

embedded/2025/2/11 20:18:16/

在使用 SQLAlchemy 进行多表映射时,我们可以使用 ORM(对象关系映射) 的方式将多个表与 Python 类进行映射。SQLAlchemy 提供了功能强大的机制,能够轻松地将数据库表和 Python 对象之间的关系建立起来。

在这里插入图片描述

1、问题背景

假设我们有一个数据库结构,由三个表组成:

items
- item_id
- item_handleattributes
- attribute_id
- attribute_nameitem_attributes
- item_attribute_id
- item_id
- attribute_id
- attribute_value

我们希望在 SQLAlchemy 中进行如下操作:

item = Item('item1')
item.foo = 'bar'session.add(item)
session.commit()item1 = session.query(Item).filter_by(handle='item1').one()
print item1.foo # => 'bar'

但是,对于 SQLAlchemy 新手来说,我们遇到了困难。虽然我们在文档中找到了相关解决方案,但它只允许将 item_idattribute_id 添加到 Item 中,而无法将属性添加到 Item 对象。

2、解决方案

我们可以在 SQLAlchemy 中通过实现“实体-属性-值模式”(Entity-Attribute-Value,EAV)来实现这种多表映射。EAV 是一种数据模型,它将实体的属性存储在一张单独的表中,而不是将它们作为实体本身的列。

一个解决方案是将属性存储在一个文本字段中。这种方法的好处在于它非常直观,并且很容易实现。但是,这种方法的缺点是无法对属性进行过滤。

另一种解决方案是使用 PostgreSQL 中的 hstore 模块,它可以存储字符串到字符串的映射。这种方法的好处是可以对属性进行过滤,但是它要求使用 PostgreSQL 数据库

下面的代码示例展示了如何使用 SQLAlchemy 实现多表映射:

class VerticalProperty(object):"""A key/value pair.This class models rows in the vertical table."""def __init__(self, key, value):self.key = keyself.value = valuedef __repr__(self):return '<%s %r=%r>' % (self.__class__.__name__, self.key, self.value)class VerticalPropertyDictMixin(object):"""Adds obj[key] access to a mapped class.This is a mixin class.  It can be inherited from directly, or includedwith multiple inheritence.Classes using this mixin must define two class properties::_property_type:The mapped type of the vertical key/value pair instances.  Will beinvoked with two positional arugments: key, value_property_mapping:A string, the name of the Python attribute holding a dict-basedrelationship of _property_type instances.Using the VerticalProperty class above as an example,::class MyObj(VerticalPropertyDictMixin):_property_type = VerticalProperty_property_mapping = 'props'mapper(MyObj, sometable, properties={'props': relationship(VerticalProperty,collection_class=attribute_mapped_collection('key'))})Dict-like access to MyObj is proxied through to the 'props' relationship::myobj['key'] = 'value'# ...is shorthand for:myobj.props['key'] = VerticalProperty('key', 'value')myobj['key'] = 'updated value']# ...is shorthand for:myobj.props['key'].value = 'updated value'print myobj['key']# ...is shorthand for:print myobj.props['key'].value"""_property_type = VerticalProperty_property_mapping = None__map = property(lambda self: getattr(self, self._property_mapping))def __getitem__(self, key):return self.__map[key].valuedef __setitem__(self, key, value):property = self.__map.get(key, None)if property is None:self.__map[key] = self._property_type(key, value)else:property.value = valuedef __delitem__(self, key):del self.__map[key]def __contains__(self, key):return key in self.__map# Implement other dict methods to taste.  Here are some examples:def keys(self):return self.__map.keys()def values(self):return [prop.value for prop in self.__map.values()]def items(self):return [(key, prop.value) for key, prop in self.__map.items()]def __iter__(self):return iter(self.keys())class Animal(VerticalPropertyDictMixin):"""An animal.Animal facts are available via the 'facts' property or by usingdict-like accessors on an Animal instance::cat['color'] = 'calico'# or, equivalently:cat.facts['color'] = AnimalFact('color', 'calico')"""_property_type = AnimalFact_property_mapping = 'facts'def __init__(self, name):self.name = namedef __repr__(self):return '<%s %r>' % (self.__class__.__name__, self.name)if __name__ == '__main__':from sqlalchemy import (MetaData, Table, Column, Integer, Unicode,ForeignKey, UnicodeText, and_, not_)from sqlalchemy.orm import mapper, relationship, create_sessionfrom sqlalchemy.orm.collections import attribute_mapped_collectionmetadata = MetaData()# Here we have named animals, and a collection of facts about them.animals = Table('animal', metadata,Column('id', Integer, primary_key=True),Column('name', Unicode(100)))facts = Table('facts', metadata,Column('animal_id', Integer, ForeignKey('animal.id'),primary_key=True),Column('key', Unicode(64), primary_key=True),Column('value', UnicodeText, default=None),)class AnimalFact(VerticalProperty):"""A fact about an animal."""mapper(Animal, animals, properties={'facts': relationship(AnimalFact, backref='animal',collection_class=attribute_mapped_collection('key')),})mapper(AnimalFact, facts)metadata.bind = 'sqlite:///'metadata.create_all()session = create_session()stoat = Animal(u'stoat')stoat[u'color'] = u'reddish'stoat[u'cuteness'] = u'somewhat'session.add(stoat)session.flush()session.expunge_all()critter = session.query(Animal).filter(Animal.name == u'stoat').one()print critter[u'color']print critter[u'cuteness']critter[u'cuteness'] = u'very'print 'changing cuteness:'metadata.bind.echo = Truesession.flush()metadata.bind.echo = Falsesession.close()

这个解决方案允许我们将属性存储在单独的表中,并且可以在 Item 对象中使用它们。

希望这个详细的解释对您有所帮助。如果您还有其他问题,请随时提出。

SQLAlchemy 的 ORM 映射功能简化了数据库操作,允许通过 Python 对象轻松地进行增删改查,同时保持数据的完整性。


http://www.ppmy.cn/embedded/161413.html

相关文章

leetcode_47全排列II

1. 题意 给一个含有重复数字的数组&#xff0c;求不重复的排列。 2. 题解 将数组进行排序&#xff0c;当回溯发生的时候&#xff0c;找到下个不重复的元素即可。 class Solution { public:void genPerm(std::vector<std::vector<int>> &ans, std::vector&l…

PySpark学习笔记5-SparkSQL

sparkSql的数据抽象有两种。 一类是data set适用于java和Scala 一类是data frame适用于java&#xff0c;Scala&#xff0c;python 将r d d转换为data frame #方式一 df spark.createDataFrame(rdd,schema[name,age]) #方式二 schema Structtype(). add(id,integertype(),nu…

高级系统架构师--第二章:软件工程

文章目录 2.1 开发模型瀑布模型原型模型V模型迭代与增量模型螺旋模型基本原理开发过程特点适用场景 基于构件的开发模型&#xff08;CBSD&#xff09;基于构件的软件工程&#xff08;CBSE&#xff09;快速应用开发&#xff08;RAD&#xff09;基本概念 统一过程&#xff08;UP/…

static在C++中的用法

类只产生一个对象。把构造函数放到private区域。这样外界就无法创建对象。 模板会造成代码的膨胀

TCP长连接、HTTP短轮询、HTTP长轮询、HTTP长连接、WebSocket的区别

1.TCP长连接 &#xff08;1&#xff09;概念&#xff1a;该连接属于传输层的协议。客户端和服务器之间建立连接后&#xff0c;不立即断开该连接&#xff0c;而是一直保持这个状态&#xff0c;以便后续数据的持续、连续传输。&#xff08;2&#xff09;应用场景&#xff1a;适合…

数字滤波器的分类

数字滤波器可以根据不同的标准进行分类&#xff0c;以下是几种常见的分类方式&#xff1a; 1. 按实现结构分类 FIR滤波器&#xff08;有限脉冲响应滤波器&#xff09; - 特点&#xff1a;系统的脉冲响应在有限时间内衰减到零。 - 优点&#xff1a;线性相位特性&#xff08;保…

Mysql优化的查询语句(1)

SQL 查询优化是一个系统性工程&#xff0c;除了你提到的几点&#xff0c;我再补充一些优化建议&#xff0c;帮助提升数据库查询效率&#xff1a; 1. 避免 SELECT *&#xff0c;只查询需要的字段 问题&#xff1a; SELECT * FROM users WHERE id 100;SELECT * 会获取表中所有…

P3654 First Step (ファーストステップ)(贪心算法)

#include<bits/stdc.h> using namespace std;int main() {int r,c,k;cin>>r>>c>>k;char a[105][105];int ans0;for(int i0;i<r;i){for(int j0;j<c;j){cin>>a[i][j];}}for(int i0;i<r;i){int cnt0; // 用来记录连续空地的数量for(int j…