I’m using the django rest framework to create an 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)
this would provide me with:
[
{
"EmpID": 1,
"EmpName": "Hashirama Senju",
"Email": "[email protected]",
"EmpLevel": "Jonin",
"EmpPosition": 1
},
{
"EmpID": 2,
"EmpName": "Tobirama Senju",
"Email": "[email protected]",
"EmpLevel": "Jonin",
"EmpPosition": 2
},
{
"EmpID": 3,
"EmpName": "Hiruzen Sarutobi",
"Email": "[email protected]",
"EmpLevel": "Jonin",
"EmpPosition": 5
}
]
what i really want is
[
{
"EmpID": 1,
"EmpName": "Hashirama Senju",
"Email": "[email protected]",
"EmpLevel": "Jonin",
"DeptName": "Hokage"
},
{
"EmpID": 2,
"EmpName": "Tobirama Senju",
"Email": "[email protected]",
"EmpLevel": "Jonin",
"DeptName": "Hokage"
},
{
"EmpID": 3,
"EmpName": "Hiruzen Sarutobi",
"Email": "[email protected]",
"EmpLevel": "Jonin",
"DeptName": "Hokage"
}
]
DeptName is in the department model . I want to combaine the results of both serializers and display it.
PS: The JSON result is just for an example. Cannot display real data.
2
Answers
add emp_dept in your fields as well
this is my response that I just get in which color_name comes from another model
this is my serializer