我想获取所有未超过FrequencyCap.ad_limit的广告。诀窍在于,每个“频次上限”行都可以定义不同的时段(最后一天,上个月,去年)。
频次上限是限制在特定时间段内展示广告的次数。
我的模型如下:
class Visit(Model):
__tablename__ = 'visits'
id = Column(Integer, primary_key=True)
visitor_id = Column(UUID, ForeignKey('visitors.id'))
ad_id = Column(Integer, ForeignKey('ads.id'))
class Visitor():
__tablename__ = 'visitors'
id = Column(Integer, primary_key=True)
visit = relationship('Visit', backref='visitor')
class Ad():
__tablename__ = 'ads'
id = Column(Integer, primary_key=True)
visit = relationship('Visit', backref='ad')
frequency_cap = relationship('FrequencyCap', uselist=False, backref='ad')
class FrequencyCap():
__tablename__ = 'frequency_cap'
id = Column(Integer, primary_key=True)
limit_ad = Column(Integer)
# period can takes values 0 (day), 1 (week), 2 (month)
period = Column(ChoiceType(PeriodType, impl=Integer()), nullable=False)
ad_id = Column(Integer, ForeignKey('ads.id', ondelete='CASCADE'))
到目前为止,我想到的是这样的:
visits = session.query(
func.count(Visit.id).label('number')).filter(
Visit.visitor == 1).filter(
Visit.type == 0).join(
Ad, Ad.id == Visit.ad_id).join(
FrequencyCap, FrequencyCap.ad_id == Ad.id).subquery()
ads_query = session.query(Ad).filter(
Ad.frequency_cap.has(FrequencyCap.limit_ad < visits.c.number))
只需访问一位访客进行的所有访问,而无需检查频次上限。 我该如何开始呢?