0

As stated in this question

With Django REST Framework, a standard ModelSerializer will allow ForeignKey model relationships to be assigned or changed by POSTing an ID as an Integer.

I am attempting to update a reverse relationship of the following format:

class Lesson(models.Model):
    name = models.TextField()

class Quiz(models.Model):
    lesson = models.ForeignKey(Lesson, related_name='quizzes', null=True)

class LessonSerializer(serializers.ModelSerializer):
    quizzes = serializers.PrimaryKeyRelatedField(queryset=Quiz.objects.all(), many=True, write_only=True)

    class Meta:
        model = Lesson
        fields = ('quizzes')

When posting an update containing an array of quiz primary keys using LessonSerializer I get TypeError: 'Quiz' instance expected, got '1'.

Is it possible to assign or change a reverse relationship by POSTing an array of primary keys?

Community
  • 1
  • 1
jsindos
  • 459
  • 6
  • 22

2 Answers2

0

You don't need special field in a serializer, DRF serializers is smart enough to figure out related field from a fields value.

class LessonSerializer(serializers.ModelSerializer):

    class Meta:
        model = Lesson
        fields = ('quizzes', 'name')

And you should pass list of ids, if there is only one value it should be a list anyway.

Ivan Semochkin
  • 8,649
  • 3
  • 43
  • 75
0

To solve this you need to create a Quiz instance first before you assign it to Lesson. Below's a small change to your code.

class Lesson(models.Model):
    name = models.TextField()

class Quiz(models.Model):
    lesson = models.ForeignKey(Lesson, related_name='quizzes', null=True)

class LessonSerializer(serializers.ModelSerializer):
    quizzes = serializers.PrimaryKeyRelatedField(queryset=Quiz.objects.all(), many=True, write_only=True)
    class Meta:
        model = Lesson
        fields = ('quizzes')

class QuizSerializer(serializers.ModelSerializer):
    class Meta:
        model = Quiz
        fields = ('name')


Create POST request with with quiz then run your post again