user15134931
user15134931

Reputation:

how to post foreign key with name of user other than id in django rest framework

hello everything is working fine, but if i want to post any dat in rest framework i need to pass the id of user , which is impractical how can i make it to accept the name of the user and post the the request, find my code below

serializers.py

class Authserializers(serializers.ModelSerializer):

    class Meta:
        model = Unique
        fields = '__all__'

views.py

 @api_view(['POST'])
 def auth_post_data(request):
     serializer = Authserializers(data=request.data)
     if serializer.is_valid():
         serializer.save()

     return Response(serializer.data)

when i type the name of the user as string it does not accept the input, plz help me in this situation

Upvotes: 2

Views: 717

Answers (1)

Felix Eklöf
Felix Eklöf

Reputation: 3720

You need to write a custom method for .create() to support a writeable nested serializer.

Then you can pass a request like this:

{
    "user": {
        "username": "SomeName"
    },
    "other_field": "value"
}

EDIT

Here's a rough example. Be advised that it has not validation to make sure the username is valid etc. And since it don't know how your models look like I can't make it specific to yours. So you'll have to modify it. Also, you should probably don't want to have __all__ on fields on a serializer with User as model.

from django.contrib.auth.models import User

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

class Authserializers(serializers.ModelSerializer):
    # Create field user, a nested serializer.
    user = UserSerializer()

    def create(self, validated_data):
        # Extract field 'user' from POST data.
        user_data = validated_data.pop('user')
        
        # Find a user with that username
        user = User.objects.get(username=user_data['username'])

        # Create instance of you model "Unique" here
        return Unique.objects.create(
            user=user,
            **validated_data # will set other fields that were passed.
        )

    class Meta:
        model = Unique
        fields = '__all__'

Upvotes: 2

Related Questions