简体   繁体   English

Django model 基于boolean字段过滤

[英]Django model filter based on boolean field

I have a user model which has fields like these,我有一个用户 model,它有这样的字段,

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

Where resigned_date will be None if is_active field is True .如果is_active字段为Trueresigned_date将为None If is_active field is False then the resigned_date field will have the date.如果is_active字段为False ,则resigned_date字段将包含日期。 I think I can explain it.我想我可以解释一下。

What I want is to queryset of users based on some DATE and is_active field.我想要的是基于某些DATEis_active字段查询用户集。

More clearly I want to get the list of employee that (is active and joined_date is less that or equal to the current date) and (is not active and resigned_date is greater that the current date)更清楚的是,我想获得( activejoined_date小于或等于当前日期)和(不activeresigned_date大于当前日期)的员工列表

The query I have written so far:到目前为止我写的查询:

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,
                 )
            )

But this is not working.但这是行不通的。 It is not returning any users.它不返回任何用户。

How can I achive this?我怎样才能做到这一点?

Thanks谢谢

I have managed to do this with this below method:我已经设法用下面的方法做到了这一点:

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))

If using single query如果使用单个查询

users = user_models.User.objects.filter(
                Q(
                    branch_id=branch_id,
                    date_joined__month__lte=month,
                    date_joined__year__lte=year,
                ),
                Q(is_active=True)
                | Q(
                    resigned_date__month__gt=month,
                    resigned_date__year__gte=year,
                ),
            )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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