基于单个对象条件的过滤查询集

时间:2019-08-06 08:29:16

标签: django-rest-framework django-queryset

我想基于用户org在对象的多对多字段中的条件返回查询集。

我的ListAPIVIew:

Students/{SubjectId}

CatalogueItem模型:

class ListCoursesView(generics.ListCreateAPIView):
    serializer_class = CourseSerializer

    def get_queryset(self):
        catalogue_items = CatalogueItem.objects.filter(tenant=self.request.user.tenant)
        org_catalogue_items = []
        organisation = self.request.user.organisation_unit.org
        for item in catalogue_items:
            if item.organisations.count() > 0:
                if organisation in item.organisations.all():
                    org_catalogue_items.append(item)
                return org_catalogue_items
        return catalogue_items

如果“组织”字段为空,我只想按租户过滤,如果“组织”为非空,我要检查登录用户的组织在“多对多”字段中。

这不会返回正确的结果。如果多对多字段为空,我想返回catalogue_items数组。如果不为空,则应基于对象是否在多对多字段中返回查询集

1 个答案:

答案 0 :(得分:1)

您不需要手动过滤多对多关系。 Django也可以过滤这种关系。因此,您可以在组织中与CatalogueItem相同的组织中检索Organization的查询集,其中self.request.user.organization_unit.org的原因是:

from django.db.models import Q

CatalogueItem.objects.filter(
    Q(organizations=self.request.user.organization_unit.org) |
    Q(organizations=None)
    tenant=self.request.user.tenant,
)