lakerskill
lakerskill

Reputation: 1079

Expected a dictionary, but got str Django Rest Framework

Right now I am creating a user department with a list of users that are a foreign key back to the main user model. I had this working yesterday, but for some reason I screwed it up. I imagine it has something to do with the serializers. I want to be able to post a list of users in this format

['jack', 'tom']

However, even using the raw data api this is not allowing me to do this. Here is my code:

Serializers:

    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']

I swear yesterday it was allowing me to select from a list of users in the api. I could also post and it would work from the front end. However, now whenever I create a department it's expecting a dictionary, which I am not trying to pass.

Upvotes: 0

Views: 687

Answers (2)

Paritosh Wadhavane
Paritosh Wadhavane

Reputation: 156

When you use the nested serializer you need to add the nested serializer field (user_department in your case) to the fields too, as you can see you used

fields = '__all__'

which does not include your nested serializer field, you need to manually add that to the meta fields

Upvotes: 0

lakerskill
lakerskill

Reputation: 1079

Dudes, for whatever reason, removing () after the UserSerializer fixed it. If anyone can explain why that would be even better!

    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']

Upvotes: 1

Related Questions