Restframework 序列化器关系获取外键字段

时间:2021-05-03 04:42:04

标签: django django-rest-framework

如何使用DRF获取另一个表的字段,使用外部字段。

我的模型 1

true

模型 2

class Teacher_lesson_price(models.Model):
    id = models.AutoField(primary_key=True)
    teacher_id = models.ForeignKey(Teacher, on_delete=models.CASCADE, null=False)
    subject_id = models.ForeignKey(Subject, related_name='subject_name_rel', on_delete=models.CASCADE, null=False)
    course_id = models.ForeignKey(Course, on_delete=models.CASCADE , null=False, default=None)
    price = models.CharField(max_length=250)

我的序列化器

class Subject(models.Model):
    id = models.AutoField(primary_key=True)
    subject_name = models.CharField(max_length=255)
    course = models.ForeignKey(Course, on_delete=models.CASCADE)

我尝试过这样,还有很多其他的例子:使用 class getSubjectall(serializers.ModelSerializer): class Meta: model = Subject fields = '__all__' class getSubjectApi(serializers.ModelSerializer): subject_name = getSubjectall(read_only=True) class Meta: model = Teacher_lesson_price fields = ['id', 'teacher_id', 'subject_id', 'course_id', 'price', 'subject_name'] 到我的 related_name 序列化器和不同类型的 getSubjectApi

serializers.fields

还是不行。

查看

subject_name_rel = serializers.ReadOnlyField(source='Subject.subject_name', read_only=True)

我需要这样的结果(类似)。我该怎么做?

@api_view(['GET'])
def subjectApiView(request):   
    teacherLessonPrice = Teacher_lesson_price.objects.filter(teacher_id = request.user.teacher.id)
    serializer = getSubjectApi(teacherLessonPrice, many=True)
    return Response(serializer.data)

1 个答案:

答案 0 :(得分:1)

您可以尝试像这样更改 getSubjectApi 序列化程序:

class getSubjectApi(serializers.ModelSerializer):
    subject = getSubjectall(source='subject_id', read_only=True)

    class Meta:
        model = Teacher_lesson_price
        fields = ['id', 'teacher_id', 'subject_id', 'course_id', 'price', 'subject']

您将收到以下回复:

[
  {
    "id": 1,
    "teacher_id": "11",
    "subject_id": 1,
    "course_id": "11",
    "price": "1000",
    "subject": {
      "id": 1,
      "subject_name": "new_subject"
    }
  },
  {
    "id": 2,
    "teacher_id": "13",
    "subject_id": 2,
    "course_id": "22",
    "price": "12222",
    "subject": {
      "id": 2,
      "subject_name": "another_subject"
    }
  }
]