Django DRF视图过滤ManyToMany查询集
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django DRF视图过滤ManyToMany查询集相关的知识,希望对你有一定的参考价值。
有两种型号,class User(Model)
和
class Loan(Model):
parents = models.ManyToManyField(User, related_name='parents', verbose_name='Родители') # .objects.all().filter(user_type=User.PARENT)
children = models.ManyToManyField(User, related_name='children', verbose_name='Дети') #.objects.all().filter(user_type=User.CHILD)
和基于DRF的视图
class ChildrenViewset(viewsets.ModelViewSet):
queryset = User.objects.all()
def get_queryset(self):
queryset = User.objects.all()
# TODO here i need to write filter
return queryset
如何过滤查询集以选择已定义父项的所有子项?
我有一些parent_identity
(可以称为id
或pk
)
我期待看到的:
queryset = User.objects.filter(children__loan_set__parent__identoty=parent_identity)
return queryset
答案
DONE
class ChildrenViewset(viewsets.ModelViewSet):
queryset = auth_models.User.objects.all()
serializer_class = auth_serializers.UserModelSerializer
def get_queryset(self):
queryset = auth_models.User.objects.all()
parent_identity = self.request.query_params.get('parent', None)
if parent_identity is not None:
queryset = queryset.filter(
Q(children__parents__identity=parent_identity) |
Q(children__parents__email=parent_identity) |
Q(children__parents__phone=parent_identity)
)
return queryset
以上是关于Django DRF视图过滤ManyToMany查询集的主要内容,如果未能解决你的问题,请参考以下文章