【问题标题】:Django model filter based on boolean field基于布尔字段的Django模型过滤器
【发布时间】:2022-10-05 12:24:16
【问题描述】:

我有一个用户模型,其中包含这样的字段,

is_active = models.BooleanField()
date_joined = models.DateTimeField(auto_now_add=True)
resigned_date = models.DateTimeField(blank=True, null=True)

如果is_active 字段为True,则resigned_date 将为None。如果is_active 字段为False,则resigned_date 字段将包含日期。我想我可以解释一下。

我想要的是基于一些 DATEis_active 字段的用户查询集。

更清楚地,我想获取(activejoined_date 小于或等于当前日期)和(不是 activeresigned_date 大于当前日期)的员工列表

到目前为止我写的查询:

users = user_models.User.objects.filter(
                Q(
                     is_active=True,
                     date_joined__month__lte=month,
                     date_joined__year__lte=year,
                 )
              & Q(
                     is_active=False,
                     resigned_date__month__gt=month,
                     resigned_date__year__gt=year,
                 )
            )

但这不起作用。它不会返回任何用户。

我怎样才能做到这一点?

谢谢

  • 这段代码的输出是什么?
  • 没有什么。只是一个黑色查询列表

标签: python django django-models django-queryset django-orm


【解决方案1】:

我已经设法用下面的方法做到了这一点:

all_users = user_models.User.objects.filter(
                branch_id=branch_id,
                date_joined__month__lte=month,
                date_joined__year__lte=year,
            )

active_users = all_users.filter(
                is_active=True,

            )
inactive_users = all_users.filter(
                is_active=False,
                resigned_date__month__gt=month,
                resigned_date__year__gte=year,
            )
users = list(chain(active_users, inactive_users))

我不知道这是唯一的方法还是有一些更有效的方法。

任何改进将不胜感激。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-15
    • 1970-01-01
    • 2020-04-09
    • 2021-11-28
    • 1970-01-01
    • 2014-03-15
    • 2012-01-14
    相关资源
    最近更新 更多