需要一本字典,但得到了str Django Rest Framework

时间:2019-03-01 01:55:07

标签: django django-models django-rest-framework

现在,我正在创建一个用户部门,其中包含用户列表,这些用户列表是返回主用户模型的外键。我昨天有这个工作,但是由于某种原因我搞砸了。我想这与序列化程序有关。我希望能够以这种格式发布用户列表

['jack', 'tom']

但是,即使使用原始数据api,这也不允许我这样做。这是我的代码:

序列化器:

    class DepartmentSerializer(serializers.ModelSerializer):
    user_department = UserSerializer(many=True)
    class Meta:
        model = Departments
        fields = '__all__'
class DepartmentUpdateSerializer(serializers.ModelSerializer):
    user_department = UserSerializer(many=True)
    class Meta:
        model = Departments
        fields = ['department_name', 'department_head', 'user_department']

我昨天发誓,这使我可以从api用户列表中进行选择。我也可以发布,它将从前端开始工作。但是,现在每当我创建一个部门时,都期望有字典,而我并不想通过。

1 个答案:

答案 0 :(得分:1)

伙计们,无论出于何种原因,请在UserSerializer修复后删除()。如果有人能解释为什么那会更好!

    class DepartmentSerializer(serializers.ModelSerializer):
    user_department = UserSerializer
    class Meta:
        model = Departments
        fields =['department_name', 'department_head', 'user_department']
class DepartmentUpdateSerializer(serializers.ModelSerializer):
    user_department = UserSerializer
    class Meta:
        model = Departments
        fields = ['department_name', 'department_head', 'user_department']