简体   繁体   English

如何在一个对象中获取键值对,同时在 Python 中的 SQLAlchemy 中连接两个表?

[英]How to get key-value pair in one object while joining two tables in SQLAlchemy in Python?

I have two tables Employee and Department, After joining I am getting a result like this我有两个表员工和部门,加入后我得到这样的结果

[
    {
      "name": "Omar Hasan",
      "id": 1,
      "email": "omar@example.com"
    },
    {
      "dept_name": "Engineering",
      "id": 2
    }
]

But I want the result in one object like但我想要一个对象的结果,比如

[
    {
      "name": "Omar Hasan",
      "id": 1,
      "email": "omar@example.com",
      "dept_name": "Engineering",
    },
    ......
    ......
]

Here is my code这是我的代码

Models, dept_id is FK in Employee table模型,dept_id 在 Employee 表中是 FK

class Employee(Base):
    __tablename__ = "employees"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, index=True)
    email = Column(String, unique=True, index=True)
    password = Column(String)
    is_active = Column(Boolean, default=True)
    salary = Column(Numeric(10, 2))
    dept_id = Column(Integer, ForeignKey('departments.id'), nullable=False)

    department = relationship("Department", back_populates="owner")

class Department(Base):
    __tablename__ = "departments"

    id = Column(Integer, primary_key=True, index=True)
    dept_name = Column(String, unique=True, index=True)

    owner = relationship("Employee", back_populates="department")

Here is the query which produces the above result这是产生上述结果的查询

return db.query(models.Employee, models.Department)\
        .join(models.Employee.department)\
        .options(
        Load(models.Employee).load_only("name", "email"),
        Load(models.Department).load_only("dept_name")
        )\
        .all()

Instead of explicitly joining the two models you can use the relationships defined between them to allow access to the department name when building the results.您可以使用它们之间定义的关系来允许在构建结果时访问部门名称,而不是显式连接这两个模型。

# Query Employee only
res = session.query(Employee)\
        .options(
        orm.Load(Employee).load_only("name", "email"),
        orm.Load(Department).load_only("dept_name")
        )\
        .all()
 
mappings = []
for employee in res:
    d = {
        'name': employee.name,
        'id': employee.id,
        'email': employee.email,
        'dept_name' employee.department.name
    }
    mappings.append(d)

We can make building the result dictionaries more elegant by defining a department name property on Employee :我们可以通过在Employee上定义一个部门名称属性来使构建结果字典更加优雅:

class Employee(Base):
    ...
    
    @property
    def dept_name(self):
        return self.department.dept_name

...

# List the attributes that we want
attrs = ['name', 'id', 'email', 'dept_name']
# Build the mappings using dictionary comprehensions
mappings = [{attr: getattr(e, attr) for attr in attrs} for e in res]

Rather than a standard property , we could use a hybrid_property instead, but there isn't much value in doing this here unless you want to use it in queries.我们可以使用hybrid_property而不是标准property ,但在这里这样做没有太大价值,除非您想在查询中使用它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python 3 如何从只包含一个未知键的键值对的字典中获取值? - Python 3 how to get value from dictionary containing only one key-value pair with unknown key? 如何获取Python中第一个键值对的值 - How to get the value of a first key-value pair in Python Python:如何检查对象的键值对的数据类型? - Python: How to check the data type of key-value pair of an object? 如何根据 Python 中的公共键值对有效地将键值从一个字典列表插入另一个字典列表? - How to efficiently insert key-value from one list of dictionaries to another based on a common key-value pair in Python? 如何从一个键有多个值的字典中获取随机键值对? - How to get a random key-value pair from dictionary where there are many values to one key? 如何根据具有两个键值对的词典列表中的另一个kv对的值创建一个键值对中的值列表 - how to create a list of values from one key-value pair based on the value of another k-v pair from a list of dictionaries with two key-value pairs 如何从 python 中的键值对中搜索键 - How to search key from key-value pair in python 如何在运行时使用python验证两个JSON API Response键值对匹配? - How to Validate two JSON API Response key-value pair matches on runtime using python? 如何从python中的两个ndarray列表创建键值对列表? - How to create key-value pair list from two list of ndarray in python? 如何将两列值转换为键值对字典? - How to convert two columns values into a key-value pair dictionary?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM