如何使用相同的外键从另一个模型访问数据?

时间:2019-05-21 12:47:17

标签: python django django-models django-rest-framework

我想使用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')

0 个答案:

没有答案