简体   繁体   中英

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 .

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.

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)). Then join Domains and MXToolboxBatch based on that result. In uber -pseudo code:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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