【问题标题】:Peewee ORM: Select based on attributes on foreign key fields (backrefs)Peewee ORM:基于外键字段(backrefs)上的属性进行选择
【发布时间】:2019-05-01 01:18:12
【问题描述】:

我正在尝试根据外键字段中的值进行选择。

我的模型如下所示:

class Domain(BaseModel):
domain_check_time = DateTimeField()
domain_name = CharField()
domain_health = BooleanField()
domain_registration_expiry_date = DateField()
domain_registration_expiry_health = BooleanField()
domain_ssl_issuer_cn = CharField()
domain_ssl_expiry_date = DateField()
domain_ssl_expiry_health = BooleanField()
domain_mxtoolbox_health = BooleanField(null = True)

class MXToolboxReport(BaseModel):
    domain = ForeignKeyField(Domain, backref = 'mxtoolbox_reports', null = True)
    command = CharField()
    response = TextField()

class MXToolboxBatch(BaseModel):
    mxtoolbox_batch_time = DateTimeField()
    domain = ForeignKeyField(Domain, backref = 'mxtoolbox_batch', null = True)
    report = ForeignKeyField(MXToolboxReport, backref = 'mxtoolbox_batch', null = True)

我正在尝试根据 mxtoolbox_batch_time 属性返回 N 个域最近的mxtoolbox_batch_time

我正在尝试用 for 循环来思考逻辑,但遇到了麻烦——我还怀疑有一种更优雅的方式。

这是我能想出的近似值(伪代码):

domains = Domain.select()

newest_batches = MXToolboxBatch.Select.limit(0)

for domain in domains:
    newest_batch = MXToolboxBatch.select().where(MXToolboxBatch.domain == domain).order_by(MXToolboxBatch.id.desc()).get()
    newest_batches += newest_batch

Domain.select().join(newest_batches).order_by(MXToolboxBatch.mxtoolbox_batch_time.desc()).limit(25)

【问题讨论】:

    标签: python python-3.x sqlite peewee


    【解决方案1】:

    与其遍历域,不如找出哪个 MXToolboxBatch 是最新的(即 max(mxtoolboxbatch_batch_time))。然后根据该结果加入 Domains 和 MXToolboxBatch。 uber中-伪代码:

    newest_batch_is = MXToolboxBatch.Select(fn.MAX(mxtoolboxbatch_batch_time))
    
    result_is = Domain.Select().join(MXToolboxBatch).where(MXToolboxBatch.batch_time = newest_batch_is).limit(N)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-15
      • 2011-08-05
      相关资源
      最近更新 更多