小编Nei*_*urn的帖子

筛选器不适用于混合属性

我正在创建的一个小型博客应用程序中实现SQLAlchemy ORM(作为Alchemy的学习练习)。我偶然发现了一些我不确定的东西-我想我知道一种方法,但是要想成为“最佳”方法可能太久了。一个表/对象具有“标题”列。我希望能够由此创建一个子弹类型的字符串。我查看了混合属性,它似乎可以解决问题。

class Post(Base):
    __tablename__ = 'posts'
    id = Column(Integer, primary_key=True)
    title = Column(String)

    @hybrid_property
    def slug(self):
        return self.title.replace(" ", "-").lower()


    def __repr__(self):
        return "<Post(id='%s', title='%s', slug='%s')>" % (
            self.id, self.title, self.slug)

post = Post(title="Hello World")
session.add(post)
session.commit()
Run Code Online (Sandbox Code Playgroud)

这对于检索值很有效:

>>> p = session.query(Post).filter(Post.title=='Hello World')
>>> p 
>>> <Post(id='1', title='Hello World', slug='hello-world')>    
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试在此属性上使用过滤器时:

>>> p = session.query(Post).filter(Post.slug=='hello-world')  
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

>>> File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/attributes.py", line 270, in __ge
tattr__
key)
AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with
Post.title has an …
Run Code Online (Sandbox Code Playgroud)

sqlalchemy

3
推荐指数
1
解决办法
1384
查看次数

python 中的“合并”时间范围

我有很多时间打开/关闭“规则”,我希望将它们合并以获得当天的一组统一规则。

from datetime import time

times = [
    {"time_open": time(9, 0), "time_close": time(11, 0)},
    {"time_open": time(9, 0), "time_close": time(12, 0)},
    {"time_open": time(13, 0), "time_close": time(18, 0)},
    {"time_open": time(15, 0), "time_close": time(19, 0)},
]

# something would produce

merged_times = [
    {"time_open": time(9, 0), "time_close": time(12, 0)},
    {"time_open": time(13, 0), "time_close": time(19, 0)},
]
Run Code Online (Sandbox Code Playgroud)

我脑子里有几种方法 - 但速度可能是所选方法的主要驱动因素。

python datetime

2
推荐指数
1
解决办法
2305
查看次数

标签 统计

datetime ×1

python ×1

sqlalchemy ×1