我有兩個型號,看起來像下面這樣:過濾嵌套關係Django的REST框架
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"
}
]
}
我的問題是,我希望檢索評估只針對特定的一年。例如,如果我作爲感興趣的年份通過,我不希望像我目前正在獲取的那樣檢索評估。
任何人都可以請協助我如何構建我的代碼,以完成此任務。先謝謝你。
編輯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
你能擴大與view.py – marin
檢查你的問題http://www.django-rest-framework.org/api-guide/serializers/#additional-keyword-arguments 。它詳細介紹瞭如何將額外參數傳遞給序列化程序。它可以幫助您構建解決方案。 –
@marin我已添加我的views.py – Tatenda