Search code examples
djangodjango-rest-frameworkdjango-filter

Django - Access nested Related Field


I have 3 models, Province, District, Commune.

And model has fields somethings like this:

Province hasMany District

District hasMany Commune

I want to access Province model from Commune through District. How can I achieve it?

My models

class Province(models.Model):
    name_eng = models.CharField(max_length=50)
    name_kh = models.CharField(max_length=50)


class District(models.Model):
    province = models.ForeignKey(
        Province, on_delete=models.CASCADE, related_name="district")
    name_eng = models.CharField(max_length=50)
    name_kh = models.CharField(max_length=50)


class Commune(models.Model):
    district = models.ForeignKey(
        District, on_delete=models.CASCADE, related_name="commune")
    name_eng = models.CharField(max_length=50)
    name_kh = models.CharField(max_length=50)

And my ModelViewset:

class CommuneFilterSet(filters.FilterSet):
   province = filters.CharFilter(field_name='province__name_kh', lookup_expr='contains')
   district = filters.CharFilter(field_name='district__name_kh', lookup_expr='contains')

   class Meta:
       model = Commune
       fields = ['district', 'province']

class CommuneViewset(viewsets.ModelViewSet):
    queryset = Commune.objects.all()
    serializer_class = CommuneSerializer
    filter_backends = (filters.DjangoFilterBackend,)
    filterset_class = CommuneFilterSet
    ordering_fields = '__all__'
    search_fields = [
        'name_kh',
        'name_eng'
    ]

Between, I use django-filter. Any help? Thanks


Solution

  • You can try like this:

    class CommuneFilterSet(filters.FilterSet):
       province = filters.CharFilter(field_name='district__province__name_kh', lookup_expr='contains')
       # rest of the code