Filtered Nested Relationships Django Rest Framework

前端 未结 2 1948
时光说笑
时光说笑 2021-01-20 22:15

I have two models which look like the following:

class Subject(models.Model):

   subject_code = models.CharField(max_length=12, unique=True)
   name = model         


        
相关标签:
2条回答
  • 2021-01-20 22:27

    Can you try with this query:

    retrieved_sub = Subject_assessment.objects.filter(subject_code__in=Subject.objects.filter(subject_code=qry_subject_code),year='2014').all()
    
    0 讨论(0)
  • 2021-01-20 22:34

    This is the solution that worked for me to this question:

    class FilteredAssessmentsSerializer(serializers.ListSerializer):
        def to_representation(self,data):
           qry_year = self.context['request'].GET.get('year')
           data = data.filter(year=qry_year)
           return super(FilteredAssessmentsSerializer,  self).to_representation(data)
    
    class AssessmentsSerializer(serializers.ModelSerializer):
       class Meta:
          model = Subject_assessment
          list_serializer_class = FilteredAssessmentsSerializer
          fields = '__all__'
    
    class SubjectSerializer(serializers.ModelSerializer):
       sub_assessments = AssessmentsSerializer(many=True)
       class Meta:
           model = Subject
           fields = (
              "subject_code", "name", "dept_code",
              "faculty_code", "university_code", "description",
              "sub_assessments"
           )
    

    Reference: I combined the following solutions to come up with one that suits me.

    How can I apply a filter to a nested resource in Django REST framework?

    https://stackoverflow.com/a/28354281/7210105

    0 讨论(0)
提交回复
热议问题