[Solved]-Django REST framework: Create/Update object using Related Field

1👍

Actually Django Rest Framework has a partial nested support. If you look at the test suite you’ll find some.
As for bitgeeky question, as said on IRC, this should work. Here’s an associated test case:
https://github.com/tomchristie/django-rest-framework/blob/2.3.13/rest_framework/tests/test_relations_nested.py#L56

Thinking about this, I think I had this error once.
@bitgeeky can you make sure you’re sending a json request by adding the content type in the header ?
By default posts will be using forms which don’t support nested.

9👍

Django REST Framework currently doesn’t support nested writes, so you will have to create the UserProfile by overriding create in a ListCreateAPIView:

class UserList(generics.ListCreateAPIView):
    model = User
    serializer_class = UserSerializer

    def create(self, request, *args, **kwargs):
        data = request.DATA

        # note: transaction.atomic was introduced in Django 1.6
        with transaction.atomic():
            user = User.(
                username=data['username'],
                ...
            )
            user.clean()
            user.save()

            UserProfile.objects.create(
                user=user,
                name=data['profile']['name']
            )

        serializer = UserSerializer(user)
        headers = self.get_success_headers(serializer.data)

        return Response(serializer.data, status=status.HTTP_201_CREATED,
                        headers=headers)

Using transaction.atomic will rollback the user creation if the profile doesn’t save successfully.

Edit

If you are creating a new user you will likely want to use the create_user method. The code above was intended to show the general case of creating a model instance and a related record in one REST API POST request.

👤Fiver

Leave a comment