[英]Peewee ORM: Select based on attributes on foreign key fields (backrefs)
I am trying to do a selection based on values in foreign key fields. 我正在尝试根据外键字段中的值进行选择。
My models look like this: 我的模型如下所示:
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)
I am trying to return N domains based on the mxtoolbox_batch_time attribute for the most recent mxtoolbox_batch_time
. 我正在尝试根据最新的
mxtoolbox_batch_time
的mxtoolbox_batch_time属性返回N个域。
I am trying o think of logic to this with for-loops but am having trouble -- I also suspect there is a more elegant way. 我正在尝试使用for循环对此进行逻辑思考,但是遇到了麻烦-我还怀疑还有一种更优雅的方法。
This is the kind of approximation I am able to come up with (pseudo code): 这是我能想到的一种近似(伪代码):
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)
Instead of looping through the domains, why not discover which MXToolboxBatch is the most recent (ie max(mxtoolboxbatch_batch_time)). 而不是遍历域,为什么不发现哪个MXToolboxBatch是最新的(即max(mxtoolboxbatch_batch_time))。 Then join Domains and MXToolboxBatch based on that result.
然后根据该结果加入Domains和MXToolboxBatch。 In uber -pseudo code:
在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.