Reputation: 181
Does django-rest framework support rearrange of models structure? I'm using the following set of models:
class Blog(models.Model):
name = models.CharField(max_length=255)
posts = models.ForeignKey(
"posts.PostsSnapshot",
on_delete=models.SET_NULL,
null=True,
blank=True
)
class PostsSnapshot(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
class Post(models.Model):
snapshot = models.ForeignKey(PostsSnapshot, on_delete=models.CASCADE, related_name='posts')
title = models.CharField(max_length=255)
content = models.TextField()
And I'm relying on ModelSerializer to provide REST access to this data:
class BlogSerializer(serializers.ModelSerializer):
posts = PostsSerializer()
class Meta:
model = Blog
fields = '__all__'
depth = 2
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ['title', 'content']
class PostsSerializer(serializers.ModelSerializer):
posts = PostsSerializer(many=True)
class Meta:
model = PostsSnapshot
fields = ['created_at', 'posts']
depth = 2
And due to that, I've got "too" nested JSON response:
"posts": {
"created_at": "2021-06-13T11:53:29.345951Z",
"posts": [
...
]
Is it possible to move the nested post data one level up? I'd like to replace the PostsSnapshotSerializer data with PostsSerializer data (but they have to be limited to this single snapshot).
Upvotes: 0
Views: 109
Reputation: 646
If you want to have a different/custom representation of your data than you have to override to_representation()
. depth
always provides nested data of your current object-data. Meta
doesn´t have a feature to level Post
and PostsSnapshot
at your Blog
-representation.
Here you can find an example.
class PostsSerializer(serializers.ModelSerializer):
posts = PostsSerializer(many=True)
class Meta:
model = PostsSnapshot
fields = ['created_at', 'posts']
def to_representation(self, data)
# make your custom representation
data['key'] = custom_values
return data
Upvotes: 1