我想使用general_info外键获取大学数据。无需在GeneralInfo序列化程序中创建college_set的嵌套序列化程序。 django rest框架是否有其他选择?我已经尝试过下面的代码行,但是它不起作用。还有其他办法吗?
college = serializers.CharField(source='general_info.college_set', read_only=True)
models.py
from django.db import models
class GeneralInfo(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
address = models.CharField(max_length=30)
class Student(models.Model):
general_info = models.ForeignKey(to=GeneralInfo, on_delete=models.PROTECT)
course = models.CharField(max_length=30)
marks = models.CharField(max_length=30)
class College(models.Model):
general_info = models.OneToOneField(to=GeneralInfo, on_delete=models.PROTECT)
name = models.CharField(max_length=30)
address = models.CharField(max_length=30)
picture = models.ImageField(null=True, blank=True, upload_to='users/')
serializer.py
from rest_framework import serializers
class MySerializer(serializers.ModelSerializer):
name = serializers.CharField(source='general_info.first_name', read_only=True)
college = serializers.CharField(source='general_info.college_set', read_only=True)
class Meta:
model = Student
fields = ('name', 'college')