Django DRF视图过滤掉ManyToMany查询集

时间:2018-11-16 15:35:40

标签: django view django-rest-framework many-to-many

有两种模型,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(可以称为idpk

我希望看到的:

queryset = User.objects.filter(children__loan_set__parent__identoty=parent_identity)
return queryset

1 个答案:

答案 0 :(得分:0)

完成

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