繁体   English   中英

Peewee ORM:根据外键字段(后向引用)的属性进行选择

[英]Peewee ORM: Select based on attributes on foreign key fields (backrefs)

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

我的模型如下所示:

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的mxtoolbox_batch_time属性返回N个域

我正在尝试使用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)

而不是遍历域,为什么不发现哪个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)

暂无
暂无

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

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