Created
May 8, 2024 17:06
-
-
Save meyt/96d19b0e7bbd6ff4ed7fa5462ed41ef1 to your computer and use it in GitHub Desktop.
Automatic nested model representation for django-restframework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db import models | |
from rest_framework import serializers | |
class MyModel(models.Model): | |
name = models.CharField(max_length=100) | |
description = models.TextField() | |
created_at = models.DateTimeField(auto_now_add=True) | |
updated_at = models.DateTimeField(auto_now=True) | |
def __str__(self): | |
return self.name | |
class MyModelSerializer(NestedModelSerializer): | |
class Meta: | |
model = MyModel | |
fields = '__all__' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from rest_framework import serializers | |
from rest_framework.utils import model_meta | |
class NestedModelSerializer(serializers.ModelSerializer): | |
def to_representation(self, instance): | |
representation = super().to_representation(instance) | |
for field_name, field in self.fields.items(): | |
if not isinstance(field, serializers.PrimaryKeyRelatedField): | |
continue | |
v = getattr(instance, field_name) | |
if not v: | |
continue | |
model = getattr(self.Meta, "model") | |
info = model_meta.get_field_info(model) | |
if field_name not in info.relations: | |
continue | |
relation_info = info.relations[field_name] | |
class Nested(serializers.ModelSerializer): | |
class Meta: | |
model = relation_info.related_model | |
fields = "__all__" | |
representation[field_name] = Nested().to_representation(v) | |
return representation |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment