Philip Mutua
Philip Mutua

Reputation: 6871

How to correctly create a POST method for nested serializers in django rest framework

I have a serializerclass which is like this:

class EmployeeSerializer(serializers.ModelSerializer):
    bio = BioSerializer()
    # designation = GroupListSerializer()
    # department = GroupListSerializer()

    class Meta:
        model = Employee
        fields = ['user','bio','tax_id_number','account_number','joining_date','designation','department']

How do I make a POST method for this in django correctly:

So far this is what I have:

class EmployeeCreateView(generics.CreateAPIView):
    queryset=Employee.objects.all()
    serializer_class=EmployeeSerializer


    def post(self, request, format=None):

        designation = Group.objects.get(id=request.data['designation'],)
        department = Group.objects.get(id=request.data['department'],)
        user =User.objects.get(id=request.data['user'],)
        bio =Bio.objects.get(id=request.data['bio'],)


        # user=User.objects.get(id=request.data['user'],)    
        employee = Employee.objects.create(
            tax_id_number=request.data['tax_id_number'],
            account_number=request.data['account_number'],
            joining_date=request.data['joining_date'],
            designation =designation,
            department =department,
            user=user,
            bio=bio,

            )

        return Response(status=status.HTTP_201_CREATE

D)

But when i make a post request I get the following in my logs:

 MultiValueDictKeyError at /hr/employee_create/
"'bio'"

Upvotes: 0

Views: 248

Answers (1)

JPG
JPG

Reputation: 88449

I don't think you need to override the create() in your views.py. Use only this, and override serializers' create() method if you want (I think that's the good strategy for DRF)

class EmployeeCreateView(generics.CreateAPIView):
    queryset=Employee.objects.all()
    serializer_class=EmployeeSerializer


request payload

{
    "user": "user data",
    "tax_id_number": 12344,
    "bio": {
        "field1": "foo",
        "field2": "bar"
    },
    "other fields": "values"

}

Upvotes: 2

Related Questions