Home > Net >  how to post manytomany field by value not by id in django rest framework
how to post manytomany field by value not by id in django rest framework

Time:10-24

I have a tow classes , the relationship between them many to many field , i wont to post data in this way {"first_name":"mohammad", "last_name":"alqudah", "motivate":[ "Stay Fit","Look Younger" ] } instead of this way {"first_name":"mohammad", "last_name":"alqudah", "motivate":[ 1,2 ] }

my Serializers

    class MotivateSerializers(serializers.ModelSerializer):
    class Meta:
        model = Motivate
        fields = ['name']

class UserSerializers(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['lat','long','first_name','last_name','mobile_number','email','date_of_birth',
        'gender','height','weight','relationship','number_of_household','number_of_pets','kind_of_pets','motivate']

my views.py


@api_view(['POST', ])
@permission_classes([IsAuthenticated])
def userdata(request):
    user = request.user
    serializer = UserSerializers(instance=user, data=request.data,many=False)
    if serializer.is_valid():
        serializer.save()
        return Response("Data has been updated successfully")
    else:
        # print (serializer.errors)
        return Response(serializer.errors)




CodePudding user response:

You can use SlugRelatedField. Example:

class UserSerializers(serializers.ModelSerializer):
    # New
    motivate = serializers.SlugRelatedField(
        slug_field="name",
        queryset=Motivate.objects.all()
        many=True
    )

    class Meta:
        model = User
        fields = [
            "first_name", "last_name",
            ...
            "motivate"
        ]
  • Related