How to get the no of times a user visited a shop on each date(activity_date) from the model using a single query

时间:2017-06-20 12:35:29

标签: django database orm

class StoreLog(models.Model):
    user_id = models.ForeignKey(User, verbose_name=_('User'), related_name='user_analytics_data', null=True, blank=True)
    store_id = models.IntegerField(verbose_name=_('Store'))
    device_id = models.TextField(
        verbose_name=_("Device ID"), db_index=True,
        help_text=_("ANDROID_ID / TelephonyManager.getDeviceId() (always as hex)")
    )
    device_type = models.TextField(verbose_name=_("Device Info"), blank=True, null=True)
    activity_date = models.DateTimeField(_('Date'), default=timezone.now)

aim: if user visits a shop more than once on a particular date a mail should be send offering some deals

1 个答案:

答案 0 :(得分:0)

假设我正确理解StoreLog对象是访问商店的用户的单个实例的记录,您可以像这样查询该表:

# Period of "the last 2 weeks"
start = datetime.datetime.now() - timedelta(days=14)
end = datetime.datetime.now()

visits = StoreLog.objects.filter(
    user_id=THEUSER,
    activity_date__range=[start, end],
)

这将返回一个查询集,其中包含过去两周内涉及该特定用户的所有StoreLog。

要计算,你只需要做

visit_count = visits.count()

从那里,您可以使用命令执行类似操作,向符合条件的用户发送电子邮件:

# Period set to just one day
start = datetime.datetime.now() - timedelta(days=1)
end = datetime.datetime.now()

for user in User.objects.all():
    visits = StoreLog.objects.filter(
        user_id=user,
        activity_date__range=[start, end],
    )
    if visits.count() > 1:
        send_email_to_user(user)

要使其特定于商店,您还需要将shop_id传递给查询条件。