过滤嵌套关系Django Rest Framework

时间:2017-02-10 10:21:37

标签: django django-rest-framework

我有两个模型,如下所示:

class Subject(models.Model):

   subject_code = models.CharField(max_length=12, unique=True)
   name = models.CharField(max_length=100)
   dept_code = models.CharField(max_length=6)

和...

class Subject_assessment(models.Model):    
   subject_code = models.ForeignKey(Subject, related_name='sub_assessments')
   year = models.CharField(max_length=4)
   name = models.CharField(max_length=50)

我已经创建了序列化,当我检索主题时,我还检索与该主题相关的评估。我使用以下序列化程序来完成此任务:

class AssessmentsSerializer(serializers.ModelSerializer):
class Meta:
    model = Subject_assessment
    fields = (
        "subject_code", "year", "name"
    )

class SubjectSerializer(serializers.ModelSerializer):
sub_assessments = AssessmentsSerializer(many=True)
class Meta:
    model = Subject
    fields = (
        "subject_code", "name", "dept_code",            
        "sub_assessments"
    )

这段代码完全符合预期,因为它给我一个这样的结果:

{
 "subject_code":"ECR2243",
 "name":"Statistics",
 "dept_code":"Stats",
 "sub_assessments":[
     {
       "subject_code":"ECR2243",
       "year":"2017",
       "name":"Test 1"
     },
     {
       "subject_code":"ECR2243",
       "year":"2016",
       "name":"Test 1"
     }
 ]
}

我的问题是我希望只检索特定年份的评估。例如,如果我通过 2017 作为感兴趣的年份,我不希望像我目前所获得的那样检索 2016 的评估。

任何人都可以协助我如何构建我的代码以实现这一目标。提前谢谢。

修改1 我的views.py如下:

class  SubjectViewSet(viewsets.ModelViewSet):
serializer_class = SubjectSerializer
lookup_field = 'subject_code'

def get_queryset(self):
    qry_subject_code = self.request.GET.get('subject_code')
    retrieved_sub = Subject.objects.filter(subject_code=qry_subject_code)
    return retrieved_sub

2 个答案:

答案 0 :(得分:3)

这是解决这个问题的解决方案:

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

参考:我结合以下解决方案,提出了一个适合我的解决方案。

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

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

答案 1 :(得分:0)

您可以尝试使用此查询:

retrieved_sub = Subject_assessment.objects.filter(subject_code__in=Subject.objects.filter(subject_code=qry_subject_code),year='2014').all()