postgresql 使用django-rest-framework序列化器获取外键值

rdlzhqv9  于 2023-01-08  发布在  PostgreSQL
关注(0)|答案(2)|浏览(143)

我使用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结果只是一个例子,不能显示真实的数据。

qyuhtwio

qyuhtwio1#

emp_dept = serializers.CharField(source='EmpPosition.DeptName')

也在字段中添加emp_dept
这是我刚刚得到的响应,其中color_name来自另一个模型

{
            "id": 6,
            "full_name": "nlah bkadkf",
            "password": "pbkdf2_sha256$390000$ELBf2Bo3t8sjFp2fQLWsnJ$eGcd29VaeqFTka/rkKIcfLRe/bbiToWd23wIHEq+8x0=",
            "username": "kashi",
            "first_name": "nlah",
            "last_name": "bkadkf",
            "email": "kashi@gmail.com",
            "address": "fkjdas",
            "mobile_number": "56789",
            "is_delete": false,
            "color_name": "Green"
        }

这是我的序列化程序

class UserSerializer(serializers.ModelSerializer):
    color_name = serializers.CharField(source='color.color_name', read_only=True)
    full_name = serializers.CharField(read_only=True)
    is_delete = serializers.BooleanField(read_only=True)

    class Meta:
        model = User
        fields = ['id', 'full_name', 'password', 'username', 'first_name', 'last_name', 'email', 'address',
                  'mobile_number', 'is_delete', 'color_name']
eoxn13cs

eoxn13cs2#

class EmployeeSerializer(serializers.ModelSerializer):

    emp_dept = serializers.CharField(source='DepartmentModel.DeptName')
    class Meta:
        model = EmployeeModel
        fields = ('EmpID','EmpName','Email','EmpLevel','emp_dept')

     def to_representation(self, instance):
        rep = super(EmployeeSerializer, self).to_representation(instance)
        rep['EmpLevel'] = instance.EmpLevel
        rep['emp_dept'] = instance.emp_dept.DeptName
        return rep

相关问题