Sk Farhad
Sk Farhad

Reputation: 1

Customizing Model Serializer for many to many fields in Django

I need some guidance to implement the serializers for models containing many to many fields in a generalized way. Suppose I have the following (hugely simplified) models:

class Operative(models.Model):
    name = models.CharField(max_length=256, blank=False)    
    email = models.EmailField(unique=True, null=True)
    desiganation = models.PositiveSmallIntegerField(default=0, choices=((0, 'Operative'), (1, 'Manager'), (2, 'Owner')))


class Task(models.Model):
    title = models.CharField(max_length=256, blank=False)
    manager = models.ForeignKey(Operative, null=True,on_delete=models.SET_NULL)
    operatives = models.ManyToManyField(Operative, blank=True)
    deadline = models.DateTimeField(null=True, blank=True)

Now if I have a serializer like this:

class TaskSerializer(ModelSerializer):

    class Meta:
        model = Task
        fields = ('id', 'title', 'manager', 'operatives', 'deadline')
        read_only_fields = ('id',)

What would be the best approach to handle the update requests containing integer ids for manager and operatives? The update API will receive POST requests containing json data like this:

{
    "id": 1002,
    "title": "Task1",
    "deadline": "2018-09-15T15:53:00+05:00",
    "manager": 55,
    "operatives": [102, 110, 324]
}

I would like to implement the customized logic for foreign keys and many to many fields inside the serializer. Currently, I am using some helper methods in the View to get/set the ids for operatives and manager and it seems a bit clumsy.

Upvotes: 0

Views: 320

Answers (2)

Tolqinbek Isoqov
Tolqinbek Isoqov

Reputation: 175

ModelSerializer handles foreign keys and many to many relations. You should override create(self, validated_data) and update(self, instance, validated_data) method to customize saving and manipulating data.

Upvotes: 0

dpdenton
dpdenton

Reputation: 310

Does the below not work?

class TaskSerializer(ModelSerializer):

    manager = serializers.PrimaryKeyRelatedField()
    operatives = serializers.PrimaryKeyRelatedField(many=True)

    class Meta:
        model = Task
        fields = ('id', 'title', 'manager', 'operatives', 'deadline')
        read_only_fields = ('id',)

Upvotes: 1

Related Questions