Home > Mobile >  django "StringRelatedField.to_internal_value() must be implemented for field " error
django "StringRelatedField.to_internal_value() must be implemented for field " error

Time:03-09

I have a model for a "gym", and a model for a "workout":

class Gym(models.Model):
    name = models.CharField(max_length=255)
    address = models.CharField(max_length=255)

    def __str__(self):
        return self.name

class Workout(models.Model):
    gym = models.ForeignKey(Gym, on_delete=models.CASCADE) 
    time = models.DateTimeField()

I will also show the 'WorkoutSerializer':

class WorkoutSerializer(serializers.ModelSerializer):
    gym = serializers.StringRelatedField()
    class Meta:
        model = Workout
        fields = ['gym','time']

as you can see, gym is represented in the workout json as a string of the field 'name'.

here is the view for workout:

@api_view(['GET','POST'])
def workout_list(request):
    if request.method == 'GET':
        queryset = Workout.objects.select_related('gym').all() 
        serializer = WorkoutSerializer(queryset, many=True)
        return Response(serializer.data)
    elif request.method == 'POST':
        serializer = WorkoutSerializer(data=request.data)
        serializer.is_valid(raise_exception=True) # rasis 400 bad request if needed
        serializer.save()
        return Response('ok')

when I try to test a POST request with (I want to use the gym's str representation in POST as well):

{ "gym": "gym 2", "activity": "Yuga", "time": "2022-03-07T06:00:00Z", "participants": [ "Anna Boing" ] }

I get the error:

StringRelatedField.to_internal_value() must be implemented for field

any idea why, and what can I do to fix this?

CodePudding user response:

StringRelatedField is a read-only field. If you want to make gym field writable you can use SlugRelatedField instead. Please note that the slug field corresponds to a model field with unique=True.

CodePudding user response:

I think StringRelatedField won't work for object creation,

Also, Gym needs an address and name both and you are just passing the name.

You can use SlugRelatedField for that.

  • Related