考虑具有关联类别的Listing模型。我想通过对数据执行POST来为现有类别创建新的列表:
{"title": "myapp", "category": {"name": "Business"}}
,其中title
是应创建的列表的标题,Business
是要用于此新列表的现有类别的名称。
当我尝试发出这样的请求并为此实例化ListingSerializer
时,我收到错误,指示类别名称必须是唯一的 - 我不想创建新的类别,但是使用而现有的。我已经尝试将类别字段上的验证器设置为[]
,但这并没有改变行为。
我可以使用SlugRelatedField
,但这会强制我的请求数据看起来更像{"title": "myapp", "category": "Business"}
,这不是我想要的。我尝试使用source
的{{1}}参数来指定嵌套关系,但这不起作用:
SlugRelatedField
的产率:
category = serializers.SlugRelatedField(
slug_field='category.name',
queryset=models.Category.objects.all()
)
models.py:
"category": [
"Object with name={'name': 'Business'} does not exist."
]
serializers.py:
import django.contrib.auth
from django.db import models
from django.conf import settings
class Profile(models.Model):
display_name = models.CharField(max_length=255)
user = models.OneToOneField(settings.AUTH_USER_MODEL)
class Category(models.Model):
name = models.CharField(max_length=50, unique=True)
description = models.CharField(max_length=200)
class Listing(models.Model):
title = models.CharField(max_length=50, unique=True)
category = models.ForeignKey(Category, related_name='listings', null=True)
owners = models.ManyToManyField(
Profile,
related_name='owned_listings',
db_table='profile_listing',
blank=True
)
views.py:
import logging
import django.contrib.auth
from rest_framework import serializers
import myapp.models as models
logger = logging.getLogger('mylogger')
class ShortUserSerializer(serializers.ModelSerializer):
class Meta:
model = django.contrib.auth.models.User
fields = ('username', 'email')
class ProfileSerializer(serializers.ModelSerializer):
user = ShortUserSerializer()
class Meta:
model = models.Profile
fields = ('user', 'display_name')
read_only = ('display_name',)
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = models.Category
fields = ('name', 'description')
read_only = ('description',)
class ListingSerializer(serializers.ModelSerializer):
owners = ProfileSerializer(required=False, many=True)
# TODO: how to indicate that this should look for an existing category?
category = CategorySerializer(required=False, validators=[])
class Meta:
model = models.Listing
depth = 2
def validate(self, data):
logger.info('inside ListingSerializer validate')
return data
def create(self, validated_data):
logger.info('inside ListingSerializer.create')
# not even getting this far...
答案 0 :(得分:3)
CategorySerializer.create
update_or_create
转换为name
方法
class CategorySerializer(serializers.ModelSerializer):
...
# update_or_create on `name`
def create(self, validated_data):
try:
self.instance = Category.objects.get(name=validated_data['name'])
self.instance = self.update(self.instance, validated_data)
assert self.instance is not None, (
'`update()` did not return an object instance.'
)
return self.instance
except Category.DoesNotExist:
return super(CategorySerializer, self).create(validated_data)
...
我建议您在需要创建自定义功能时查看DRF
source。
相关问题由DRF
的创建者回答:django-rest-framework 3.0 create or update in nested serializer
所以我仍然处于DRF 2心态,自动处理嵌套的可写字段。您可以在此处阅读此主题:http://www.django-rest-framework.org/topics/3.0-announcement/
我已经测试了以下代码并且它可以运行:
class CategorySerializer(serializers.ModelSerializer):
class Meta:
...
extra_kwargs = {
'name': {'validators': []},
'description': {'required': False},
}
class ListingSerializer(serializers.ModelSerializer):
...
def update_or_create_category(self, validated_data):
data = validated_data.pop('category', None)
if not data:
return None
category, created = models.Category.objects.update_or_create(
name=data.pop('name'), defaults=data)
validated_data['category'] = category
def create(self, validated_data):
self.update_or_create_category(validated_data)
return super(ListingSerializer, self).create(validated_data)
def update(self, instance, validated_data):
self.update_or_create_category(validated_data)
return super(ListingSerializer, self).update(instance, validated_data)
使用SlugRelatedField
的正确方法是这样的,以防您想知道:
class ListingSerializer(serializers.ModelSerializer):
...
# slug_field should be 'name', i.e. the name of the field on the related model
category = serializers.SlugRelatedField(slug_field='name',
queryset=models.Category.objects.all())
...
答案 1 :(得分:3)
这不太理想,但我确实找到了解决问题的解决方案(我等待接受它作为答案,希望别人能做得更好)。分为两部分:
首先,在初始化partial=True
(http://www.django-rest-framework.org/api-guide/serializers/#partial-updates)时使用ListingSerializer
参数。然后使用序列化程序的validate
方法获取与输入数据对应的实际模型实例。
其次,明确删除name
中CategorySerializer
字段的验证程序。这尤其糟糕,因为它影响的不仅仅是ListingSerializer
。
退出任何一块将导致在实例化序列化器时抛出验证错误。
对views.py的修改:
class ListingViewSet(viewsets.ModelViewSet):
queryset = models.Listing.objects.all()
serializer_class = serializers.ListingSerializer
def create(self, request):
serializer = serializers.ListingSerializer(data=request.data,
context={'request': request}, partial=True)
if not serializer.is_valid():
logger.error('%s' % serializer.errors)
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
对serializers.py的修改:
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = models.Category
fields = ('name', 'description')
read_only = ('description',)
# also need to explicitly remove validators for `name` field
extra_kwargs = {
'name': {
'validators': []
}
}
class ListingSerializer(serializers.ModelSerializer):
owners = ProfileSerializer(required=False, many=True)
category = CategorySerializer(required=False)
class Meta:
model = models.Listing
depth = 2
def validate(self, data):
# manually get the Category instance from the input data
data['category'] = models.Category.objects.get(name=data['category']['name'])
return data
def create(self, validated_data):
title = validated_data['title']
listing = models.Listing(title=validated_data['title'],
category=validated_data['category'])
listing.save()
if 'owners' in validated_data:
logger.debug('owners: %s' % validated_data['owners'])
for owner in validated_data['owners']:
print ('adding owner: %s' % owner)
listing.owners.add(owner)
return listing
我会稍等一下接受这个作为答案以防有人能提出更好的解决方案(比如如何使source
参数与SlugRelatedField
正常工作) - 我有如果您想进行实验,请使用上面https://github.com/arw180/drf-example解决方案的工作示例。我也很想听到关于extra_kwargs
中为什么CategorySerializer
这些东西是必要的评论 - 为什么不像这样实例化category = CategorySerializer(required=False, validators=[])
就足够了(ListingSerializer
)?更新:我认为这不起作用,因为独特的验证器是从数据库约束中自动添加的,无论在此处设置任何显式验证器都会运行,如本答案中所述:http://iswwwup.com/t/3bf20dfabe1f/python-order-of-serializer-validation-in-django-rest-framework.html
答案 2 :(得分:1)
我有类似的问题:我需要检查嵌套序列化程序(CategorySerializer
)是否存在,如果是,则使用它,如果不存在 - 从嵌套序列化程序(ListingSerializer
)创建它。只有当我没有对嵌套序列化器中的字段使用自定义验证时,@ demux的解决方案才对我有用(如果此实例存在,我将通过嵌套序列化程序检查该字段)。因此,我将create()
方法添加到嵌套序列化程序,并将update_or_create_category()
,create()
,update()
ListingSerializer
添加到class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
...
def create(self, validated_data):
if Category.objects.filter(name=self.validated_data['name']).exists():
raise serializers.ValidationError("This category name already exists")
return Category.objects.create(**validated_data)
。
Mysecret.objects.filter(creator=request.user).delete()