【问题标题】:FIlter query set based on condition on individual object根据单个对象的条件过滤查询集
【发布时间】:2019-12-13 18:17:37
【问题描述】:

我想根据用户组织在对象的多对多字段中的条件返回一个查询集。

我的列表APIVIew:

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

CatalogueItem 型号:

class CatalogueItem(Enrollable):
    admin_only = models.BooleanField(default=False)
    organisations = models.ManyToManyField(Organisation, blank=True)

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

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

【问题讨论】:

  • 可否分享相关模型并说明您要检索的什么
  • 好的@WillemVanOnsem

标签: django-rest-framework django-queryset


【解决方案1】:

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

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,
)

【讨论】:

    猜你喜欢
    • 2018-05-27
    • 1970-01-01
    • 1970-01-01
    • 2016-05-05
    • 2019-09-15
    • 2019-10-08
    • 2019-07-27
    • 1970-01-01
    • 2015-10-28
    相关资源
    最近更新 更多