gpt4 book ai didi

django - 使用 Django Rest Framework 3.2.2 与现有对象的可写嵌套序列化器

转载 作者:行者123 更新时间:2023-12-03 02:00:21 27 4
gpt4 key购买 nike

考虑一个具有关联类别的列表模型。我想通过使用数据进行 POST 来为现有类别创建一个新列表:{"title": "myapp", "category": {"name": "Business"}},其中 title 是应创建的列表的标题,Business 是用于此新列表的现有类别的名称。

当我尝试发出此类请求并为此实例化 ListingSerializer 时,我收到一条错误,指示类别名称必须是唯一的 - 我不想创建新类别,但是使用现有的代替。我尝试将类别字段上的验证器设置为 [],但这并没有改变行为。

我可以使用 SlugRelatedField,但这会迫使我的请求数据看起来更像 {"title": "myapp", "category": "Business"} ,这不是我想要的。我尝试使用 SlugRelatedFieldsource 参数来指定嵌套关系,但这也不起作用:

category = serializers.SlugRelatedField(
slug_field='category.name',
queryset=models.Category.objects.all()
)

产量:

  "category": [
"Object with name={'name': 'Business'} does not exist."
]

模型.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
)

序列化器.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...

views.py:

import logging

from django.http import HttpResponse
from django.shortcuts import get_object_or_404

import django.contrib.auth

from rest_framework import viewsets
from rest_framework.response import Response

import myapp.serializers as serializers
import myapp.models as models


# Get an instance of a logger
logger = logging.getLogger('mylogger')

class CategoryViewSet(viewsets.ModelViewSet):
queryset = models.Category.objects.all()
serializer_class = serializers.CategorySerializer

class UserViewSet(viewsets.ModelViewSet):
queryset = django.contrib.auth.models.User.objects.all()
serializer_class = serializers.ShortUserSerializer

class ProfileViewSet(viewsets.ModelViewSet):
queryset = models.Profile.objects.all()
serializer_class = serializers.ProfileSerializer

class ListingViewSet(viewsets.ModelViewSet):
logger.info('inside ListingSerializerViewSet')
queryset = models.Listing.objects.all()
serializer_class = serializers.ListingSerializer

完整示例:https://github.com/arw180/drf-example

最佳答案

这并不理想,但我确实找到了解决我的问题的解决方案(我正在等待接受它作为答案,希望其他人可以做得更好)。有两部分:

首先,使用partial=True初始化 ListingSerializer 时的参数(http://www.django-rest-framework.org/api-guide/serializers/#partial-updates)。然后使用序列化器的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

关于django - 使用 Django Rest Framework 3.2.2 与现有对象的可写嵌套序列化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32123148/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com