Django Rest Framework中Foreignkey字段的动态选择

时间:2016-12-02 02:59:44

标签: python django rest django-rest-framework

我刚刚开始学习Django Rest Framework并试图使用Django rest Framework制作一个简单的API。

这是我的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()]

在模型的“choices =”字段中,但它没有用完。

提前致谢。

1 个答案:

答案 0 :(得分:2)

我认为您正在寻找DRF文档的this part

基本上,使用了Django模型自己的表示。例如,在Student模型中,您可以添加__str__方法:

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

Django的Meta选项文档是here,请查找model methods