我是DRF序列化的新手,我在这里遇到小问题......
models.py
class roles(models.Model):
role = models.IntegerField(primary_key = True)
type = models.CharField(max_length = 20)
one = models.CharField(max_length = 20)
class Meta:
db_table = 'roles'
class employees(models.Model):
name = models.CharField(max_length=25)
mobileno = models.IntegerField()
roletype = models.ForeignKey(roles,related_name='emps')
class Meta:
db_table = 'employees'
serializers.py
class rSerializer(serializers.ModelSerializer):
class Meta:
model = roles
fields = ('type','one')
class eSerializer(serializers.ModelSerializer):
class Meta:
model = employees
fields = ('name','mobileno')
views.py
@csrf_exempt
@api_view(['GET'])
def accesstwo(request):
if request.method == 'GET':
#emp = employees.objects.all()
#serializer = eSerializer(emp, many=True)
#return JSONResponse({"resource":serializer.data})
emp = employees.objects.get(id = 1)
serializer = eSerializer(emp, many=False)
return JSONResponse(serializer.data)
如果我运行上面的代码,我得到的结果如下。
{
"name": "emp01",
"mobileno": 23434
},
但在这里我想使用下面的序列化器从两个表中获取数据。
{
"name": "emp01",
"mobileno": 23434,
"type":"manager",
"one":"test"
}
如何在python DRF服务中执行此操作?。
答案 0 :(得分:2)
您必须在rSerializer()
中传递eSerializer()
。请检查下面提到的更新代码:
class eSerializer(serializers.ModelSerializer):
roles = rSerializer()
class Meta:
model = employees
fields = ('name','mobileno', 'roles')