I have 2 models: Document and Source. These 2 models have a many-to-many relationship like this. Within Source, I would like to have an array of Documents.
class Document(models.Model):
id = models.BigAutoField(primary_key=True)
uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
# lots of other fields
class Source(models.Model):
id = models.BigAutoField(primary_key=True)
uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
references = models.ManyToManyField(Document, blank=True)
# lots of other fields
I've created a DocumentUUIDSerializer, that is seperate from DocumentSerializer, to only contain the uuids, ie. just so its lighter. Within my SourceSerializer, I use this new lighter serializer.
class DocumentUUIDSerializer(serializers.ModelSerializer):
uuid = serializers.UUIDField(read_only=True)
class Meta:
model = Document
fields = ("uuid",)
class SourceSerializer(serializers.ModelSerializer):
# other serializers
references = DocumentUUIDSerializer(required=False, many=True)
class Meta:
model = Source
exclude = ["id"]
def create(self, validated_data):
print(validated_data)
# lots more code
For some reason, however, the first output is from my ModelViewSet:
{'references': [{'uuid': 'd74b1941-8270-4a85-adea-9e2fb19332f6'}], 'title': 'GGs', 'content': {}, 'author': 'Sidd Mittal', 'url': 'http://example.com'}
And this output is from my create function:
{'references': [OrderedDict()], 'title': 'GGs', 'content': {}, 'author': 'Sidd Mittal', 'url': 'http://example.com'}
references simply becomes an empty OrderedDict, and I can't seem to figure out why. I've tried adding multiple print statements, and it's clear that there seems to be an error with the DocumentUUIDSerializer, but I can't understand where. Any help would be greatly appreciated 🙂