回到顶部

阅读目录

Django DateTimeField 指定日期筛选(How can I filter a date of a DateTimeField in Django)

models.py

class AnchorBindAgent(models.Model):
    """
    主播绑定到代理,绑定规则
    """
    end_time_default = (timezone.now() + timezone.timedelta(days=15)).date()

    agent = models.ForeignKey(verbose_name="代理绑定", to=User, on_delete=models.DO_NOTHING)
    anchor = models.ForeignKey(verbose_name="主播名称", to=Anchor, on_delete=models.DO_NOTHING)
    proportion = models.FloatField(verbose_name="分成比例(%)", default=10, help_text="0 到 100 整数或小数")

    start_time = models.DateField(verbose_name="生效日期", default=timezone.now)
    end_time = models.DateField(verbose_name="失效日期", default=end_time_default)

    create_time = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)  # timezone.now 不要加括号
    update_time = models.DateTimeField(verbose_name="更新时间", auto_now=True)

views.py

def yesterday_new_anchor(request):
    """
    我的主播
    :param request:
    :return:
    """
    title = "昨日绑定主播"
    description = "列出您昨日绑定的主播"

    # 昨日
    # yesterday = datetime.now() - timedelta(days=1)
    yesterday = timezone.now() - timezone.timedelta(days=1, hours=0, minutes=0, seconds=0)
    # 昨日绑定主播
    anchors = AnchorBindAgent.objects.order_by("-create_time").filter(
        agent=request.user,
        create_time__year=yesterday.year,
        create_time__month=yesterday.month,
        create_time__day=yesterday.day
    )

我如上代码写的 date 过滤,只要筛选到月份就没数据了,实际上是有的数据得:

>>> AnchorBindAgent.objects.order_by("-create_time").filter(agent__username="fjiabinc").filter(create_time__year=yesd.year)[1]
<AnchorBindAgent: fjiabinc_ID:724313097_昵称:一生只宠@@@婷_15.0>
>>> AnchorBindAgent.objects.order_by("-create_time").filter(agent__username="fjiabinc").filter(create_time__year=yesd.year)[1].create_time
datetime.datetime(2020, 4, 21, 9, 53, 48, 959740, tzinfo=<UTC>)
>>> yesd
datetime.datetime(2020, 4, 21, 15, 46, 1, 849153, tzinfo=<UTC>)
>>> AnchorBindAgent.objects.order_by("-create_time").filter(agent__username="fjiabinc").filter(create_time__year=yesd.year, create_time__month=yesd.month)
<QuerySet []>

解决方案:

anchors = AnchorBindAgent.objects.order_by("-create_time").filter(
    agent=request.user,
    create_time__contains=yesterday.date()
)

 

^_^
请喝咖啡 ×

文章部分资料可能来源于网络,如有侵权请告知删除。谢谢!

前一篇: 解压压缩软件无广告 bandizip 6.26 版本下载
下一篇: Why you should use the Django admin: 9 tips