我想创建一个雇员对象,其属性包括预先存在的外键(部门)。当我看到雇员api ..我正在获取部门ID而不是部门名称.. python - Django REST FRAMEWORK中的外键关系-LMLPHP ..请帮助

models.py

class Department(models.Model):
name = models.CharField(max_length= 20)
def __str__(self):
    return self.name

class Employee(models.Model):
employee_name = models.CharField(max_length= 20)
surname = models.CharField(max_length= 20)
address = models.CharField(max_length  = 50)
qualification = models.CharField(max_length = 30)
contact_num = PhoneNumberField()
department = models.ForeignKey(Department, on_delete=models.PROTECT)
def __str__(self):
    return self.employee_name


序列化

class DepartmentSerializer(serializers.ModelSerializer):
""" Serializer to represent the Chain model """
    class Meta:
        model = Department
        fields = '__all__'


class EmployeeSerializer(serializers.ModelSerializer):
    """ Serializer to represent the Chain model """
    class Meta:
        model = Employee
        fields = '__all__'

最佳答案

您可以使用StringRelatedField()相同。

class EmployeeSerializer(serializers.ModelSerializer):
    """ Serializer to represent the Chain model """
    department = serializers.StringRelatedField()
    class Meta:
        model = Employee
        fields = '__all__'



  StringRelatedField可以使用其__unicode____str__方法来表示关系的目标。




如果希望查看与该FK相关的所有详细信息,请使用以下depth

class EmployeeSerializer(serializers.ModelSerializer):
    """ Serializer to represent the Chain model """

    class Meta:
        model = Employee
        fields = '__all__'
        depth = 1

关于python - Django REST FRAMEWORK中的外键关系,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51238469/

10-12 18:13