我需要过滤个人记录的结果,以便只有作为某个程序成员的用户才能从该个人那里获得未过期的信息。
示例:
当Sam通过FoodDelivery程序列出他可以访问的所有人时,Mike最初应该出现在搜索中。
当expiration_date__lte ='今天'时,版本已过期 当发行版到期时,迈克不应再出现了。
我已经确定了这一点,用户只能看到具有任何版本的个人记录,这些记录列出了授权的用户程序。但expiration_date被忽略,实质上使得发布无限期。
如何将已发布程序列表过滤到仅发布未过期的程序?,以便我可以使用该列表与用户程序匹配?
```python #相关类的简化代码。
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="user_profile")
program_list = models.ManyToManyField('Program', blank=True,)
class Program(models.Model):
name = models.CharField(max_length=100, blank=True, default='')
individual_list = models.ManyToManyField(
'Individual',
related_name='program_individual_list',
through='ReleaseAuthorization',
blank=True
)
class Individual(models.Model):
name = models.CharField(max_length=100, blank=True, default='')
authorized_program_list = models.ManyToManyField(
'Program',
related_name='individual_authorized_program_list',
through='ReleaseAuthorization',
blank=True
)
class ReleaseAuthorization(models.Model):
individual = models.ForeignKey(
Individual,
related_name="release_authorization_individual",
on_delete=models.CASCADE
)
program = models.ForeignKey(
Program,
related_name="release_authorization_program",
on_delete=models.CASCADE
)
expiration_date = models.DateField()
class IndividualViewSet(model.ModelViewSet):
model = Individual
queryset = Individual.objects.order_by('id').distinct('id')
serializer_class = IndividualSerializer
filter_backends = (filters.SearchFilter, DjangoFilterBackend)
action_serializers = {
'list': IndividualListSerializer,
}
filter_fields = ('id', 'household', 'deceased')
search_fields = ('first_name','last_name','dob')
def get_queryset(self):
user = self.request._user
user_agency_program_list = user.user_profile.program_list
user_program_list = [val.id for val in user_agency_program_list.order_by('id')]
q = Q()
q &= Q(created_by=user) # Allow if the record was created by the current user
q |= Q(authorized_program_list__in=user_program_list) # Allow if there is a match between the list of authorized programs and the user programs
# q |= Q(authorized_program_list.filter(expiration_date__lte=datetime.Date())__in=user_program_list) # Invalid Syntax, but shows what I'm trying to do
queryset = Individual.objects.filter(q).distinct('modified_at','id')
return queryset
```
答案 0 :(得分:1)
因此,如果我的问题得到了解决,您希望向所有尚未过期的个人展示该版本,那么您必须这样做:
Individual.objects.filter(release_authorization_individual__expiration_date__gt='today')
其中gt
代表大于
如果您需要,可以使用lt
(小于),lte
(小于或等于),gte
(大于或等于)
全部都在documentation