django DRF嵌套序列化程序返回空字典

tquggr8v  于 2023-01-10  发布在  Go
关注(0)|答案(2)|浏览(214)

我有两个模态名称和UserModal

class DesignationModal(models.Model):
    designation=models.CharField(max_length=100)

    def __str__(self):
        return self.designation


class UserModal(AbstractUser):
    username=models.CharField(max_length=300,unique=True)
    password=models.CharField(max_length=300)
    email=models.EmailField(max_length=300)
    designation=models.ForeignKey(DesignationModal,on_delete=models.CASCADE,
                              related_name="desig",null=True)

    def __str__(self):
        return self.username

每个用户只有一个指定。2我为此写了序列化器。

class DesignationSerializer(serializers.Serializer):
    class Meta:
        model=DesignationModal
        fields=['designation','id']

class UserSerializer(serializers.ModelSerializer):
    designation=DesignationSerializer(read_only=True,many=False)

    class Meta:
        model=UserModal
        fields=['id', 'username','designation']

我得到的JSON响应如下所示

{
"status": true,
"data": [
    
    {
        "id": 3,
        "username": "akhil",
        "designation": {}
    }
]

}
字典中没有值,当我像这样重写序列化器代码时。

class UserSerializer(serializers.ModelSerializer):
    designation=serializers.StringRelatedField()
    
    class Meta:
        model=UserModal
        fields=['id', 'username','designation']

我正在获取字符串形式的指定值

{
"status": true,
"data": [
   
    {
        "id": 3,
        "username": "akhil",
        "designation": "agent"
    }
]

}
为什么我不能用以前的方法得到值

fcipmucu

fcipmucu1#

使用depth选项将获得嵌套值。

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserModal
        fields = ['username', 'email', 'designation', ]
        depth = 1
9rbhqvlz

9rbhqvlz2#

DesignationSerializer(serializers.Serializer)的继承不正确,您需要这样更改它

class DesignationSerializer(serializers.ModelSerializer):
    class Meta:
        model=DesignationModal
        fields=['designation','id']

相关问题