gpt4 book ai didi

python - 将 sql 查询初始化为数据类

转载 作者:行者123 更新时间:2023-12-05 03:36:57 24 4
gpt4 key购买 nike

目标是根据字段的一些手动分类实现SQL中的选定列,例如

from dataclasses import dataclass


@dataclass
class Q:
fruits = ('taste', 'color', 'shine')
vege = ('is_green', 'color', 'juiceable')
meat = ('is_white', 'is_dark', 'is_red', 'meat_name')
carbs = ('is_refined', 'gi')

@static_method
def get_fields(self, add_fruits=False, add_vege=False, add_meat=False, add_carbs=False):
fields = set()
fields.update(self.fruits) if add_fruits else None
fields.update(self.vege) if add_vege else None
fields.update(self.meat) if add_meat else None
fields.update(self.carbs) if add_carbs else None
return sorted(",".join(sorted(fields)))


print(f"SELECT {Q.get_fields(add_fruits=True, add_vege=True)} from food_features")

给定 Q 对象中的大量字段类别列表,我们如何避免在 .get_fields 函数中进行硬编码?

fields.update(self._field_name_) if add_field_name else None 

最佳答案

这是您正在寻找的输出/功能吗?

class Q :
def __init__(self):
self.categories = {
'fruits': ('taste', 'color', 'shine'),
'vege': ('is_green', 'color', 'juiceable'),
'meat': ('is_white', 'is_dark', 'is_red', 'meat_name'),
'carbs': ('is_refined', 'gi')
}

def get_fields(self, groups):
fields = []
for group in groups:
fields.extend(self.categories[group])
return", ".join(sorted(set(fields)))

value = Q()
print(f"SELECT {value.get_fields(['fruits', 'vege'])} FROM food_features")

输出:

SELECT color, is_green, juiceable, shine, taste FROM food_features

关于python - 将 sql 查询初始化为数据类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69520555/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com