Question

I've worked with .NET application that communicates with database via LINQ/Entity Framework. There if we would like to go deeper into fields we just call .Include("Field"). For example suppose we have model User

public class User
{
    public long Id {get; set; }
    public string Username {get; set; }
}

and another model

public class Post
{
    public long Id {get; set; }
    public User Author {get; set; }
}

Then if we want to extract all posts we write

var posts = Repository.Posts;

The result will be just Queryable, but after executing it becomes the list of all post with authors' ids. If we want to have full User model in Author field for each post we just call

var posts = Repository.Posts.Include("Author");

After executing the list of all posts will contain posts with full users.

Now I'm working with django + django rest framework. With the same scheme to extract all posts I use serializer with the following code

from rest_framework.serializers import ModelSerializer

class PostSerializer(ModelSerializer):
    author = serializers.Field(source='author.id')

    class Meta:
        model = PostModel
        fields = ['id', 'author']

I tried to write almost everything instead of author = serializers.Field(source='author.id') but it always failed. Is there any way to get the list of all posts containing full authors' models? Surely There is. What is the best aproach to do it?

Was it helpful?

Solution

This is not the full analogue, but something similar. The solution is to define UserSerializer extending ModelSerializer like that

from rest_framework.serializers import ModelSerializer

class UserSerializer(ModelSerializer):

    class Meta:
        model = UserModel
        fields = ['id', 'username']

and then use it in PostSerializer:

from myapp import UserSerializer
from rest_framework.serializers import ModelSerializer

class PostSerializer(ModelSerializer):
    author = UserSerializer()

    class Meta:
        model = PostModel
        fields = ['id', 'author']
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top