繁体   English   中英

如何使用 peewee 将字段作为 set() 返回

[英]How to return field as set() using peewee

我目前使用 Peewee 与 ORM 一起工作,我一直在尝试了解如何从表中获取字段url 条件是visible的列也需要为真。 这意味着如果visible为 True 且store_id4则返回所有url设置。

我目前已经做了这样的事情

from peewee import (
    Model,
    TextField,
    BooleanField
)
from playhouse.pool import PooledPostgresqlDatabase

# -------------------------------------------------------------------------
# Connection to Postgresql
# -------------------------------------------------------------------------
postgres_pool = PooledPostgresqlDatabase(
    'xxxxxxx',
    host='xxxxxxxx',
    user='xxxxxxxx',
    password='xxxxxx',
    max_connections=20,
    stale_timeout=30,
)


# ------------------------------------------------------------------------------- #

class Products(Model):
    store_id = TextField(column_name='store_id')
    url = TextField(column_name='url')
    visible = BooleanField(column_name='visible')

    class Meta:
        database = postgres_pool
        db_table = "develop"

    @classmethod
    def get_urls(cls):
        try:
            return set([i.url for i in cls.select().where((cls.store_id == 4) & (cls.visible))])
        except Products.IntegrityError:
            return None

然而,使用该方法大约需要 0.13 秒,这对我来说感觉比它应该做的要长,我认为这是由于 for 循环并且需要将其作为set()并且我想知道是否有可能 peewee可以做类似cls.select(cls.url).where((cls.store_id == 4) & (cls.visible)的事情并作为 set() 返回吗?

你有多少产品? 这一套有多大? 为什么不使用distinct()以便数据库为您删除重复数据? 你有什么索引? 所有这些问题都比“我如何使这个 python 循环更快”更相关。

我建议您在store_id, visiblestore_id where visible上需要一个索引。

create index "product_urls" on "products" ("store_id") where "visible"

您甚至可以使用覆盖索引,但这可能会占用大量磁盘空间:

create index "product_urls" on "products" ("store_id", "url") where visible

使用索引加快实际查询速度后,您还可以使用distinct()使数据库在将 URL 发送到 Python 之前对 URL 进行重复数据删除。 此外,由于您只需要 URL,因此只需 select 该列并使用tuples()方法来避免创建 class:

@classmethod
def get_urls(cls):
    query = cls.select(cls.url).where((cls.store_id == 4) & cls.visible)
    return set(url for url, in query.distinct().tuples())
    

最后请阅读文档: http://docs.peewee-orm.com/en/latest/peewee/querying.html#iterating-over-large-result-sets

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM