简体   繁体   中英

RelatedManager' object has no attribute 'description

I perform request http://167.71.57.114/api2/workout-exercises/3 I want to receive data about WorkoutExercise object number 3 (detail view)

Got AttributeError when attempting to get a value for field description on serializer ExerciseSerializer . The serializer field might be named incorrectly and not match any attribute or key on the RelatedManager instance. Original exception text was: 'RelatedManager' object has no attribute 'description'.

serializers.py

class WorkoutExerciseSerializer(serializers.ModelSerializer):
    exercises = ExerciseSerializer()

    class Meta:
        model = WorkoutExercise
        fields = ('week', 'exercises')

views.py

class WorkoutExerciseViewSet(viewsets.ModelViewSet):
    queryset = WorkoutExercise.objects.all()
    serializer_class = WorkoutExerciseSerializer
    http_method_names = ['get', 'post']

models.py

class WorkoutExercise(models.Model):
    workout_program = models.ForeignKey(WorkoutProgram, on_delete=models.CASCADE, related_name='workout_exercises')
    week = models.PositiveIntegerField(default=1)
    day = models.PositiveIntegerField(default=1)
    order = models.PositiveIntegerField(default=1)

    def save(self, *args, **kwargs):
        if not self.pk:
            last_order = WorkoutExercise.objects.all().aggregate(largest=models.Max('order'))['largest']
            if last_order is not None:
                self.order = last_order + 1
        return super(WorkoutExercise, self).save(*args, **kwargs)

    def get_workout_programs(self):
        return self.workout_program.name

    def get_exercises(self):
        pass

    def __str__(self):
        return self.workout_program.name

    class Meta:
        ordering = ('week', 'day')

Based on the fact that exercises is plural, and RelatedManager error, it means that there are multiple Exercises , so you need to serialize these with a many=True parameter:

class WorkoutExerciseSerializer(serializers.ModelSerializer):
    exercises = ExerciseSerializer()

    class Meta:
        model = WorkoutExercise
        fields = ('week', 'exercises')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM