0

我有以下 Django 模型:

class Pa(models.Model):
   pa_name = models.CharField

class Pb(models.Model):
    pa = models.ForeignKey(Pa, related_name="pbs")
    pb_name = models.CharField()

class Pc(models.Model):
    pb = models.ForeignKey(Pb, related_name="pcs")
    pc_name = models.CharField()

的查询集Pc具有以下结构:

[
  { "id": 1,
    "pc_name": "pc_1",
    "pb" = {
      "id": 10,
      "pb_name": "pb_1",
      "pa" : {
        "pa_name" : "pa_1"  # <-- How to filter queryset by pa_name attribute?
      }
    }
  },
  { "id": 2,
    "pc_name": "pc_2",
    "pb" = {
      "id": 20,
      "pb_name": "pb_2",
      "pa" : {
        "pa_name" : "pa_2"
      }
    }
  },
  # ...
]

我想返回所有那些Pcs,在哪里pa_name"pa_1"即过滤 2. 级嵌套对象。

4

2 回答 2

1

可以使用链式过滤器:

pcs = Pc.objects.filter(pb__pa__pa_name=pa_name)
于 2021-07-11T21:15:56.827 回答
0

您可以编写自己的过滤器类,然后定义要过滤的内容:

import django_filters.rest_framework
import django_filters.filters

class FilterClass(django_filters.rest_framework.FilterSet):
    pb = django_filters.CharFilter(
        method="filter_pa", label="Pa filter"
    )
    class Meta:
        model = models.Pc
        fields = { 
            "pc_name": ["icontains"],
        }
    
    def filter_pb(self, queryset, field_name, value):
        return queryset.filter(
            pb__pb_name__icontains=value
        ).distinct()

class PC(APIView):
    filterset_class = FilterClass

因此,此过滤器集将允许您过滤您的pb_name. 希望这个答案能帮助您解决问题。

于 2021-07-12T07:49:13.497 回答