django.core.exceptions.FieldError:无法将关键字'department_name'解析为字段

5sxhfpxr  于 2023-01-21  发布在  Go
关注(0)|答案(2)|浏览(240)

如何正确使用序列化程序. SlugRelatedField?
我的代码看起来像这样,但它得到了一个错误...
这里有一个完整的错误:
django.core.exceptions.FieldError:无法将关键字'department_name'解析为字段。选项包括:工卡,创建时间,部门,部门标识,性别,标识,姓名,职位,职位标识,更新时间
型号代码:

class Employee(models.Model):
    GENDER_CHOICES = (
        ('Male', 'Male'),
        ('Female', 'Female'),
    )
    name = models.CharField(max_length=100)
    badge = models.CharField(max_length=6, unique=True)
    gender = models.CharField(max_length=20, choices=GENDER_CHOICES)
    department = models.ForeignKey(
        Department, on_delete=models.CASCADE, null=True)
    position = models.ForeignKey(
        Position, on_delete=models.CASCADE, null=True)
    updated_at = models.DateTimeField(auto_now=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f'{self.name} - {self.badge}'

串行器代码

from rest_framework import serializers
from .models import Employee

class EmployeeSerializer(serializers.ModelSerializer):
    department = serializers.SlugRelatedField(
        slug_field='department_name', queryset=Employee.objects.all())
    # position = serializers.SlugRelatedField(
    #     slug_field='position_name', queryset=Employee.objects.all()

    class Meta:
        model = Employee
        fields = '__all__'
k7fdbhmy

k7fdbhmy1#

在序列化程序代码中,执行以下操作

slug_field='department', queryset=Employee.objects.all())

这是因为在“Employee”模型类中没有任何名为“department_name”的字段。

iswrvxsc

iswrvxsc2#

你确定SlugFiled是最好的选择吗?
要获取部门名称,可以使用以下命令:

department = serializers.CharField(source="department.department_name")

但是你的部门FK是可以为空的,这个更好

class EmployeeSerializer(serializers.ModelSerializer):
    department = serializers.SerializerMethodField()

    class Meta:
        model = Employee
        fields = '__all__'

    @staticmethod
    def get_department(obj):
        return obj.department.department_name if obj.department else None

相关问题