我使用djangorest框架来创建一个API。
models.py
class DepartmentModel(models.Model):
DeptID = models.AutoField(primary_key=True)
DeptName = models.CharField(max_length=100)
def __str__(self):
return self.DeptName
class Meta:
verbose_name = 'Department Table'
class EmployeeModel(models.Model):
Level_Types = (
('Genin', 'Genin'),
('Chunin', 'Chunin'),
('Jonin', 'Jonin'),
)
EmpID = models.AutoField(primary_key=True)
EmpName = models.CharField(max_length=100)
Email = models.CharField(max_length=100,null=True)
EmpLevel = models.CharField(max_length=20, default="Genin", choices=Level_Types)
EmpPosition = models.ForeignKey(DepartmentModel, null=True, on_delete=models.SET_NULL)
class Meta:
verbose_name = 'EmployeeTable' # Easy readable tablename - verbose_name
def __str__(self):
return self.EmpName
serializer.py
from appemployee.models import EmployeeModel,DepartmentModel
class EmployeeSerializer(serializers.ModelSerializer):
emp_dept = serializers.CharField(source='DepartmentModel.DeptName')
class Meta:
model = EmployeeModel
fields = ('EmpID','EmpName','Email','EmpLevel','emp_dept')
views.py
class EmployeeTable(APIView):
def get(self,request):
try:
emp_obj = EmployeeModel.objects.all()
empserializer = EmployeeSerializer(emp_obj,many=True)
except Exception as err:
return Response(err)
return Response(empserializer.data)
这将为我提供:
[
{
"EmpID": 1,
"EmpName": "Hashirama Senju",
"Email": "hashirama.senju@konaha.com",
"EmpLevel": "Jonin",
"EmpPosition": 1
},
{
"EmpID": 2,
"EmpName": "Tobirama Senju",
"Email": "tobirama.senju@konaha.com",
"EmpLevel": "Jonin",
"EmpPosition": 2
},
{
"EmpID": 3,
"EmpName": "Hiruzen Sarutobi",
"Email": "hiruzen.sarutobi@konaha.com",
"EmpLevel": "Jonin",
"EmpPosition": 5
}
]
我真正想要的是
[
{
"EmpID": 1,
"EmpName": "Hashirama Senju",
"Email": "hashirama.senju@konaha.com",
"EmpLevel": "Jonin",
"DeptName": "Hokage"
},
{
"EmpID": 2,
"EmpName": "Tobirama Senju",
"Email": "tobirama.senju@konaha.com",
"EmpLevel": "Jonin",
"DeptName": "Hokage"
},
{
"EmpID": 3,
"EmpName": "Hiruzen Sarutobi",
"Email": "hiruzen.sarutobi@konaha.com",
"EmpLevel": "Jonin",
"DeptName": "Hokage"
}
]
DeptName在department模型中。我想合并两个序列化程序的结果并显示它。
PS:JSON结果只是一个例子,不能显示真实的数据。
2条答案
按热度按时间qyuhtwio1#
也在字段中添加emp_dept
这是我刚刚得到的响应,其中color_name来自另一个模型
这是我的序列化程序
eoxn13cs2#