我想在我的网站上设置restful API。我使用了django rest框架。
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile',on_delete=models.CASCADE)
name = models.CharField(max_length=30)
family = models.CharField(max_length=50)
下面是我的第二个模型(子模型):
class Klass(models.Model):
title = models.CharField(max_length=50)
description = models.CharField(max_length=500)
teacher = models.ForeignKey(Profile,related_name='teacher', on_delete=models.CASCADE)
university = models.CharField(max_length=50, blank=True, null=True)
teacher
Profile
模型
pk
.
# serializer
class KlassSerializer(serializers.ModelSerializer):
class Meta:
model = Klass
fields = ('id', 'title', 'description', 'teacher')
# view
class KlassView(APIView):
def get(self, request, pk=None):
if pk is not None:
klass = Klass.objects.filter(pk=pk).get()
serializer = KlassSerializer(klass)
return Response({'message': 'class get ', 'data': serializer.data,})
结果如下:
{
"message": "class get ",
"data": {
"id": 13,
"title": "ÙThe First Class",
"description": "Nothing for now!",
"teacher": 2
}
}
我怎样才能解决这个问题?
谢谢