'Why can't I add a ManyToMany relation to an object in Django?

I've got an api made in Django which has two models linked by a ManyToMany relation.

class Type(models.Model):
    name = models.CharField(max_length=64)
    application = models.CharField(max_length=64)
    description = models.TextField()

class Device(models.Model):
    reference = models.CharField(max_length=64)
    application = models.CharField(max_length=64)
    types = models.ManyToManyField(to='Type')

I'm using Django Rest Framework, in which I've got a create() method in the serializer to add types to a device.

def create(self, validated_data):
    # Serialize Types
    types_data = validated_data.pop('types')
    device = Device.objects.create(**validated_data)
    print("DEVICE TYPE",type(device))
    for type_data in types_data:
        print("TYPE OF TYPE_DATA", type(type_data))
        print("TYPE_DATA", type_data)
        t = Type.objects.create(device=device, **type_data)
        print("TYPE", t)
        device.types.add(t)

    print("TYPES IN OBJECT", device.types)
    device.save()
    return device

Unfortunately it doesn't seem to work. I've got some print statements in the code above, and the outpunt of that is:

DEVICE TYPE <class 'iot.models.Device'>
TYPE OF TYPE_DATA <class 'collections.OrderedDict'>
TYPE_DATA OrderedDict([('name', 'Serve north.'), ('application', 'Particular outside.'), ('description', 'Teacher rather.')])
TYPE Type object (1)
TYPES IN OBJECT iot.Type.None

As you can see at the last line, the Types don't seem to be added.

What am I doing wrong here?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source