Django DRF 视图过滤多对多查询集
Posted
技术标签:
【中文标题】Django DRF 视图过滤多对多查询集【英文标题】:Django DRF views filter ManyToMany queryset 【发布时间】:2018-11-16 15:35:40 【问题描述】:有两种型号,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
【问题讨论】:
【参考方案1】:完成
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 视图过滤多对多查询集的主要内容,如果未能解决你的问题,请参考以下文章