Serializer Extensions

The ‘serializer’ module provides additional functionality to Django REST framework’s serializer classes by adding the ManyToManyField and ManyToManySerializer classes.

It offers a ManyToManyField class that allows for the serialization and deserialization of many-to-many relationships, which are commonly used in Django models. The ManyToManyField class supports the full range of many-to-many fields, including fields with intermediate models and related objects.

In addition, this module provides a ‘ManyToManySerializer’ class that can be used as a base class for serializers that handle many-to-many relationships. It is designed to simplify the creation of custom serializers with many-to-many fields.

Let’s take a quick look at the following example:

 1from mastf.MASTF.serializers import ManyToManySerializer, ManyToManyField
 2
 3# Define a new class with many-to-many relationships
 4class BlogSerializer(ManyToManySerializer):
 5    rel_fields = ("articles", )
 6    articles = ManyToManyField(Article, mapper=int)
 7
 8    class Meta:
 9        model = Blog
10        fields = '__all__'

Here, we’ve created a new class named BlogSerializer that uses a ManyToManyField to represent a many-to-many relationships. In addition, we delcared a mapper function that will convert incoming data to the preferred primary key attribute.

Enhanced Fields and Serializers

class mastf.MASTF.serializers.ManyToManyField(*args, **kwargs)[source]

Implementation of a Many-To-Many relation for REST-Framework serializers.

As described in the ManyToManyField class for Django forms, the behaviour of this almost the same. It will convert multiple database objects by placing their primary key (or specified field name) and de- serialize JSON lists or strings into qualified database model objects.

class AuthorSerializer(serializers.Serializer):
    books = ManyToManySerializer(Book, mapper=int)

In this example, we have defined a simple serializer that will convert a list of Book objects into JSON and vice versa. Note that mapper argument that is necessary if the primary key is of type int.

Warning

The validated data returned by this field is a tuple that stores the retrieved elements and whether they should be replaced with the current database values or should be added. Therefore you can add a special keyword to the start of the transmitted data:

1data = {
2    "field_name": [
3        # Indicates the following values will replace any existing values;
4        # leave that value out if you want to add objects to existing values.
5        "$set",
6        "pk1",
7        "pk2", ...
8    ]
9}
Parameters:
  • model (class<? extends Model>) – The Django model class

  • delimiter (str) – The string delimiter to use when splitting the input string

  • field_name (str) – The field name to query

  • mapper (Callable[T, [str]]) – A conversion function to optionally convert input keys

to_internal_value(data: str) tuple[source]

Transform the incoming primitive data into a native value.

to_representation(value: list)[source]

Transform the outgoing native value into primitive data.

class mastf.MASTF.serializers.ManyToManySerializer(*args, **kwargs)[source]

Helper class to simplify updating Many-To-Many relationships.

This class is an extended version of a ModelSerializer and should only be used on serializer classes that use ManyToManyField definitions. It implements the update() function which adds selected objects to a many-to-many relationship.

In order to achieve a flawless update, the rel_fields must contain all field names that are related to many-to-many relationships:

class AuthorSerializer(ManyToManySerializer):
    rel_fields = ("books",)
    books = ManyToManyField(Book, mapper=int)

    class Meta: # don't forget to specify the model
        model = Author
        fields = '__all__'
rel_fields = None

The fields related to a many-to-many relationship.