sqlalchemy, hybrid property case statement

2024/11/16 15:16:09

This is the query I'm trying to produce through sqlalchemy

SELECT "order".id AS "id", 
"order".created_at AS "created_at", 
"order".updated_at AS "updated_at", 
CASE 
WHEN box.order_id IS NULL THEN "special" 
ELSE "regular" AS "type"
FROM "order" LEFT OUTER JOIN box ON "order".id = box.order_id

Following sqlalchemy's documentation, I tried to achieve this using hybrid_property. This is what I have so far, and I'm not getting the right statement. It is not generating the case statement properly.

from sqlalchemy import (Integer, String, DateTime, ForeignKey, select, Column, create_engine)
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.hybrid import hybrid_propertyBase = declarative_base()
class Order(Base):__tablename__ = 'order'id = Column(Integer, primary_key=True)created_at = Column(DateTime)updated_at = Column(DateTime)order_type = relationship("Box", backref='order')@hybrid_propertydef type(self):if not self.order_type:return 'regular'else:return 'special'class Box(Base):__tablename__ = 'box'id = Column(Integer, primary_key=True)monthly_id = Column(Integer)order_id = Column(Integer, ForeignKey('order.id'))stmt = select([Order.id, Order.created_at, Order.updated_at, Order.type]).\select_from(Order.__table__.outerjoin(Box.__table__))
print(str(stmt))
Answer

The hybrid property must contain two parts for non-trivial expressions: a Python getter and a SQL expression. In this case, the Python side will be an if statement and the SQL side will be a case expression.

from sqlalchemy import case
from sqlalchemy.ext.hybrid import hybrid_property@hybrid_property
def type(self):return 'special' if self.order_type else 'regular'@type.expression
def type(cls):return case({True: 'special', False: 'regular'}, cls.order_type)
https://en.xdnf.cn/q/71323.html

Related Q&A

Whats the newest way to develop gnome panel applets (using python)

Today Ive switched to GNOME (from XFCE) and found some of the cool stuff missing and I would like to (try to) do them on my own. I tried to find information on how to develop Gnome applets (items you p…

How to install opencv-python in python 3.8

Im having problem during the installation of opencv-python in pycharm. After opening pycharm I click on settings and then project interpreter, I click on + and search for the correct module, I started …

python augmented assignment for boolean operators

Does Python have augmented assignment statements corresponding to its boolean operators?For example I can write this:x = x + 1or this:x += 1Is there something I can write in place of this:x = x and yT…

Change a pandas DataFrame column value based on another column value

I have a dataframe with two columns each of which represents an organism. They are called ORG1 and ORG2 I want to move the values of ORG2 into ORG1 for the corresponding index value.So, if ORG1 is A a…

How to lock a sqlite3 database in Python?

Is there a way to explicitly acquire a lock on a sqlite3 database in Python?

How to install pyzmq on an Alpine Linux container?

I have a container with the python:3.6-alpine kernel. I have a problem installing the pyzmq via pip on this: Dockerfile: FROM python:3.6-alpineRUN mkdir /code RUN apk add vim WORKDIR / ADD . /codedocke…

How to Get Value Out from the Tkinter Slider (Scale)?

So, here is the code I have, and as I run it, the value of the slider bar appears above the slider, I wonder is there a way to get that value out? Maybe let a=that value. ;)from Tkinter import *contr…

Python cassandra-driver OperationTimeOut on every query in Celery task

I have a problem with every insert query (little query) which is executed in celery tasks asynchronously. In sync mode when i do insert all done great, but when it executed in apply_async() i get this:…

Function which returns the least-squares solution to a linear matrix equation

I have been trying to rewrite the code from Python to Swift but Im stuck on the function which should return the least-squares solution to a linear matrix equation. Does anyone know a library written i…

Divide .csv file into chunks with Python

I have a large .csv file that is well over 300 gb. I would like to chunk it into smaller files of 100,000,000 rows each (each row has approximately 55-60 bytes).I wrote the following code:import panda…