2014-05-07 74 views
3

我有兩個型號:如何在django rest框架中將相關字段包含到模型序列化中?

class User(models.Model): 
    username = models.CharField() 

class Post(models.Model): 
    text = models.TextField() 
    owner = models.ForeignKey(User) 

使用這種串行:

from rest_framework.serializers import ModelSerializer 

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

    class Meta: 
     model = Post 
     fields = ['text', 'owner'] 

我得到業主的ID的所有帖子。如何修改序列化程序以獲取包含所有用戶模型的擁有者的所有帖子?

我tryied 從rest_framework.serializers導入ModelSerializer

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

    class Meta: 
     model = Post 
     fields = ['text', 'owner'] 

但僅替換用戶名ID,而不是如我所料,型號全(因爲用戶表示將返回用戶名字段)。

回答

6

的解決方案是定義UserSerializer延伸ModelSerializer那樣

from rest_framework.serializers import ModelSerializer 

class UserSerializer(ModelSerializer): 

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

,然後在PostSerializer使用它:

from myapp import UserSerializer 
from rest_framework.serializers import ModelSerializer 

class PostSerializer(ModelSerializer): 
    owner = UserSerializer() 

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

使用您ModelSerializerMeta類中depth選項:

class PostSerializer(ModelSerializer): 

    class Meta: 
     model = Post 
     fields = ['text', 'owner'] 
     depth = 1 

還要注意的是,你並不需要包括Author領域。

Docs here

+0

這是錯字。修正了 – sbeliakov

+0

而關於解決方案。這不完全是我想要的。我想擴大唯一的領域,而不是所有領域的深度。 – sbeliakov

相關問題