POST 带有 ID 和 GET 的嵌套对象不能在 Django 中同时在 ModelSerializer 中工作
POST with an ID and GET the nested object does not work in django at the same time in ModelSerializer
我已经花了几天时间在类似问题中研究这个问题,但我无法得到解决方案。这应该很简单,我有一个模型:
model.py
class Item(models.Model):
"""Class to represent an item..."""
label = models.TextField(null=True)
name = models.TextField()
category = models.ForeignKey( "Category", on_delete=models.SET_NULL,
null=True, default=DEFAULT_CATEGORY_ID)
class Category(models.Model):
"""Class to represent the category of an Item. Like plants, bikes..."""
name = models.TextField()
description = models.TextField(null=True)
view.py
class ItemViewset(viewsets.ModelViewSet): # pylint: disable=too-many-ancestors
"""API Endpoint to return the list of items"""
queryset = Item.objects.all()
serializer_class = ItemSerializer
serializer.py
class ItemSerializer(serializers.ModelSerializer):
"""Serializer for Item."""
category = CategorySerializer(read_only=True)
class Meta: # pylint: disable=too-few-public-methods
"""Class to represent metadata of the object."""
model = Item
fields = [ 'id', 'label', 'name', 'category']
read_only_fields = ['id']
# def to_representation(self, instance):
# ret = super().to_representation(instance)
# ret['category'] = CategorySerializer(instance.category).data
# return ret
def create(self, request):
# Look up objects by arbitrary attributes.
# You can check here if your students are participating
# the classes and have taken the subjects they sign up for.
category = get_object_or_404(Category(), id=request.data.get('category'))
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save(category=category)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
如果我对行 category = CategorySerializer(read_only=True)
进行了注释,则嵌套获取将不起作用,例如对对象的卷曲。我将只获得结构的 de id。如果我像示例中那样取消注释,我会得到正确的响应:
{
"id": 60,
"label": null,
"name": "Delete me",
"category": {
"id": 1,
"name": "IT"
}
}
但是这样带id的post就不行了,category会被置为null。
如何让两者同时工作?
更新:这是post我想做的:
{
"label": "00000003",
"name": "Delete me",
"category": 1,
}
您可以覆盖序列化程序的 to_represention
方法
class ItemSerializer(serializers.ModelSerializer):
"""Serializer for Item."""
class Meta: # pylint: disable=too-few-public-methods
"""Class to represent metadata of the object."""
model = Item
fields = [ 'id', 'label', 'name', 'category']
read_only_fields = ['id']
def to_representation(self, instance):
data = super().to_representation(instance)
data["category"] = CategorySerializer(instance.category).data
return data
我已经花了几天时间在类似问题中研究这个问题,但我无法得到解决方案。这应该很简单,我有一个模型:
model.py
class Item(models.Model):
"""Class to represent an item..."""
label = models.TextField(null=True)
name = models.TextField()
category = models.ForeignKey( "Category", on_delete=models.SET_NULL,
null=True, default=DEFAULT_CATEGORY_ID)
class Category(models.Model):
"""Class to represent the category of an Item. Like plants, bikes..."""
name = models.TextField()
description = models.TextField(null=True)
view.py
class ItemViewset(viewsets.ModelViewSet): # pylint: disable=too-many-ancestors
"""API Endpoint to return the list of items"""
queryset = Item.objects.all()
serializer_class = ItemSerializer
serializer.py
class ItemSerializer(serializers.ModelSerializer):
"""Serializer for Item."""
category = CategorySerializer(read_only=True)
class Meta: # pylint: disable=too-few-public-methods
"""Class to represent metadata of the object."""
model = Item
fields = [ 'id', 'label', 'name', 'category']
read_only_fields = ['id']
# def to_representation(self, instance):
# ret = super().to_representation(instance)
# ret['category'] = CategorySerializer(instance.category).data
# return ret
def create(self, request):
# Look up objects by arbitrary attributes.
# You can check here if your students are participating
# the classes and have taken the subjects they sign up for.
category = get_object_or_404(Category(), id=request.data.get('category'))
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save(category=category)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
如果我对行 category = CategorySerializer(read_only=True)
进行了注释,则嵌套获取将不起作用,例如对对象的卷曲。我将只获得结构的 de id。如果我像示例中那样取消注释,我会得到正确的响应:
{
"id": 60,
"label": null,
"name": "Delete me",
"category": {
"id": 1,
"name": "IT"
}
}
但是这样带id的post就不行了,category会被置为null。
如何让两者同时工作?
更新:这是post我想做的:
{
"label": "00000003",
"name": "Delete me",
"category": 1,
}
您可以覆盖序列化程序的 to_represention
方法
class ItemSerializer(serializers.ModelSerializer):
"""Serializer for Item."""
class Meta: # pylint: disable=too-few-public-methods
"""Class to represent metadata of the object."""
model = Item
fields = [ 'id', 'label', 'name', 'category']
read_only_fields = ['id']
def to_representation(self, instance):
data = super().to_representation(instance)
data["category"] = CategorySerializer(instance.category).data
return data