0

I have the following Django models:

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

The queryset of Pc has this structure:

[
  { "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"
      }
    }
  },
  # ...
]

I'd like to return all those Pcs, where pa_name is "pa_1", i.e. filter over the 2. level nested object.

2 Answers 2

2

Possible using a chained filter:

pcs = Pc.objects.filter(pb__pa__pa_name=pa_name)
Sign up to request clarification or add additional context in comments.

Comments

0

You can write your own filter class then define what you want to filter:

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

So this filter set will allow you to filter your pb_name. Hope this answer will help you to solve your problem.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.