在 GET 请求中检索相关字段的对象,否则仅使用 POST、PUT、DELETE 等中对象的 ID
Retrieve related field's object in GET requests, otherwise use only ID of the object in POST, PUT, DELETE etc
我有两个序列化程序。文章中的 'category' 字段是外键。
我想在执行 GET 请求时完全检索类别对象。当我执行 POST、PUT 或 DELETE 请求时,我只想使用类别的 ID。
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ('pk', 'name', 'slug')
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = ('pk', 'title', 'slug', 'body', 'category')
depth = 1
如果我将 "depth = 1" 属性 添加到 Meta class,那么我将获得类别对象。没关系。
但是,如果我尝试添加新文章(通过 POST 请求),我会收到此错误:
IntegrityError at /api/articles
NOT NULL constraint failed: panel_article.category_id
如果我尝试定义一个 CategorySerializer 字段,而不是像这样使用 'depth' 属性:
class ArticleSerializer(serializers.ModelSerializer):
category = CategorySerializer()
class Meta:
model = Article
fields = ('pk', 'title', 'slug', 'body', 'category')
由于类别字段,我收到此错误:
"Invalid data. Expected a dictionary, but got int."
当我尝试创建新文章时,我猜 DRF 正在尝试创建新类别。
我该如何解决这个问题?
这是一个常见问题,每次当你想改变表示行为时,你可以自由使用序列化器的to_representation
方法:
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Provider
fields = ('pk', 'title', 'slug', 'body', 'category')
def to_representation(self, instance):
representation = super(ArticleSerializer, self).to_representation(instance)
representation['category'] = CategorySerializer(instance.category).data
return representation
我有两个序列化程序。文章中的 'category' 字段是外键。
我想在执行 GET 请求时完全检索类别对象。当我执行 POST、PUT 或 DELETE 请求时,我只想使用类别的 ID。
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ('pk', 'name', 'slug')
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = ('pk', 'title', 'slug', 'body', 'category')
depth = 1
如果我将 "depth = 1" 属性 添加到 Meta class,那么我将获得类别对象。没关系。
但是,如果我尝试添加新文章(通过 POST 请求),我会收到此错误:
IntegrityError at /api/articles
NOT NULL constraint failed: panel_article.category_id
如果我尝试定义一个 CategorySerializer 字段,而不是像这样使用 'depth' 属性:
class ArticleSerializer(serializers.ModelSerializer):
category = CategorySerializer()
class Meta:
model = Article
fields = ('pk', 'title', 'slug', 'body', 'category')
由于类别字段,我收到此错误:
"Invalid data. Expected a dictionary, but got int."
当我尝试创建新文章时,我猜 DRF 正在尝试创建新类别。
我该如何解决这个问题?
这是一个常见问题,每次当你想改变表示行为时,你可以自由使用序列化器的to_representation
方法:
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Provider
fields = ('pk', 'title', 'slug', 'body', 'category')
def to_representation(self, instance):
representation = super(ArticleSerializer, self).to_representation(instance)
representation['category'] = CategorySerializer(instance.category).data
return representation