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

时间:2018-11-29 02:58:36

标签: python python-3.x sqlite peewee

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

我的模型如下:

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)

1 个答案:

答案 0 :(得分:0)

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