Doug Smith
Doug Smith

Reputation: 580

How to use the Django DRF serializer for ManyToManyField

I'm trying to write a serializer for my models which has a ManyToManyField. My problem seems to be very similar to this example, but at this time I'm not interested in using a SlugField and nevertheless it's not clear to me what my problem is.

models.py

class Objective(models.Model):
    objective_name = models.CharField(max_length=10)
    objective_description = models.CharField(max_length=30)

    def __str__(self):
        return self.objective_name

class Assessment(models.Model):
    objective = models.ManyToManyField(Objective)
    date_completed = models.DateField(auto_now_add=True)

serializers.py

class AssessmentSerializer(serializers.ModelSerializer):
    objective = serializers.PrimaryKeyRelatedField(many=True, read_only=True)

    class Meta:
        model = Assessment
        fields = ['name', 'date_completed', 'objective']

class ObjectiveSerializer(serializers.ModelSerializer):
    class Meta:
        model = Objective
        fields = '__all__'

From the DRF docs, I thought that the following POST would create an Assessment object where I already have two Objective objects with id's of 3 and 4 respectively.

{
    "name": "Quiz 3",
    "objective": [
        3,
        4
    ]
}

However, this creates the Assessment object but there is no link between it and the Objectives.

{
    "name": "Quiz 3",
    "date_completed": "2020-03-17",
    "objective": []
}

Is my serializer incorrect, or am I using wrong syntax for the POST, or is there a different issue?

Upvotes: 0

Views: 276

Answers (1)

JPG
JPG

Reputation: 88499

You have set read_only=True--(drf doc) in the objective field. If you set a field as read_only, DRF will not take the input data.

class AssessmentSerializer(serializers.ModelSerializer):
    objective = serializers.PrimaryKeyRelatedField(many=True, read_only=True, queryset=Objective.objects.all())

    class Meta:
        model = Assessment
        fields = ['name', 'date_completed', 'objective']

Upvotes: 1

Related Questions