2016-12-02 95 views
1

我剛開始學習Django Rest框架並嘗試使用Django rest框架製作一個簡單的API。Django Rest框架中的Foreignkey字段中的動態選擇

這是我的models.py

from __future__ import unicode_literals 
from django.db import models 

class Student(models.Model): 
    created = models.DateTimeField(auto_now_add=True) 
    name = models.CharField(max_length=150, blank=False) 
    student_id = models.CharField(max_length=20, primary_key=True) 
    father_name = models.CharField(max_length=150) 
    mother_name = models.CharField(max_length=150) 

    class Meta: 
     ordering = ('student_id',) 


class Subject(models.Model): 
    created = models.DateTimeField(auto_now_add=True) 
    subject_id = models.CharField(max_length=20, primary_key=True) 
    name = models.CharField(max_length=150) 

    class Meta: 
     ordering = ('subject_id',) 


class Result(models.Model): 
    created = models.DateTimeField(auto_now_add=True) 
    grade = models.DecimalField(max_digits=5, decimal_places=3, blank=False) 
    student_id = models.ForeignKey(Student, on_delete=models.CASCADE) 
    subject_id = models.ForeignKey(Subject, on_delete=models.CASCADE) 

    class Meta: 
     ordering = ('created',) 

這是我serializers.py

from rest_framework import serializers 
from models import * 


class StudentSerializer(serializers.HyperlinkedModelSerializer): 
    class Meta: 
     model = Student 
     fields = ('student_id', 'name', 'father_name', 'mother_name') 


class SubjectSerializer(serializers.HyperlinkedModelSerializer): 
    class Meta: 
     model = Subject 
     fields = ('subject_id', 'name') 


class ResultSerializer(serializers.HyperlinkedModelSerializer): 
    class Meta: 
     model = Result 
     fields = ('grade', 'student_id', 'subject_id') 

在我的 「結果」 的模式,我有兩個外鍵; student_id和subject_id。這是它的樣子:

enter image description here

我的問題是,我怎麼能顯示在下拉中流露出「學生對象」和「標的物」代替菜單中的「名稱」字段?

我已經在模型中的「選擇=」字段

STUDENT_CHOICES = [(each.student_id, each.name) for each in Student.objects.all()] 
SUBJECT_CHOICES = [(each.subject_id, each.name) for each in Subject.objects.all()] 

嘗試,但它沒有工作。

在此先感謝。

回答

1

我認爲您正在尋找DRF文檔的this part

基本上,你的Django模型自己的表示被使用。因此,例如,在你的Student模型,你可以添加__str__方法:Django的

# this is for Python 3, use __unicode__ on Python 2 
def __str__(self):   
    return self.name 

元文檔選項是here,尋找model methods

+0

非常感謝。它的工作:D –

+0

不客氣:) –

相關問題