TL; DR: DRF在验证最外面的序列化程序时删除内部序列化对象。
我正在使用django 2.0,django-rest-framework 3.7.7,python 3。
我想构建一个REST端点,使用POST中收到的一些参数在数据库中执行搜索(我想避免可以缓存的GET调用)。参数应该像OR一样(这就是我将所有字段设置为不需要的原因),并且我在解压缩查询集时使用django Q queries来解决这个问题。
我在app/models.py
中有以下django模型:
class Town(models.Model):
name = models.CharField(max_length=200)
province = models.CharField(max_length=2, blank=True, null=True)
zip = models.CharField(max_length=5)
country = models.CharField(max_length=100)
class Person(models.Model):
name = models.CharField(max_length=100)
birth_place = models.ForeignKey(Town, on_delete=models.SET_NULL,
null=True, blank=True,
related_name="birth_place_rev")
residence = models.ForeignKey(Town, on_delete=models.SET_NULL,
null=True, blank=True,
related_name="residence_rev")
我在app/serializers.py
中编写了以下序列化程序:
class TownSerializer(serializers.ModelSerializer):
class Meta:
model = models.Town
fields = ("id", "name", "province", "zip", "country")
def __init__(self, *args, **kwargs):
super(TownSerializer, self).__init__(*args, **kwargs)
for field in self.fields:
self.fields[field].required = False
class PersonSerializer(serializers.ModelSerializer):
birth_place = TownSerializer(read_only=True)
residence = TownSerializer(read_only=True)
class Meta:
model = models.Person
fields = ("id", "name", "birth_place", "residence")
def __init__(self, *args, **kwargs):
super(PersonSerializer, self).__init__(*args, **kwargs)
for field in self.fields:
self.fields[field].required = False
然后我在api/views.py
中编写了一个提供REST接口的视图:
class PersonSearchList(views.APIView):
model_class = Person
serializer_class = PersonSerializer
permission_classes = (permissions.AllowAny,)
def post(self, request, format=None):
serializer = self.serializer_class(data=request.data)
print("initial_data", serializer.initial_data) ########
if serializer.is_valid():
self.data = serializer.validated_data
print(self.data) ########
queryset = self.get_queryset()
serialized_objects = self.serializer_class(queryset, many=True)
return Response(serialized_objects.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def get_queryset(self, *args, **kwargs):
orig_queryset = self.model_class.objects.all()
query_payload = self.data
# .. perform filtering using the query_payload data.
return queryset
当我尝试使用例如执行查询时卷曲:
$ curl -s -X POST -H "Content-Type: application/json" --data '{"birth_place": {"name": "Berlin", "country": "Germany"}}' http://127.0.0.1:8000/persons/ |python -m json.tool
[]
即使刚刚创建了相应设置了birth_place的Person对象。 我在视图的post方法中放置的两个print语句返回:
initial_data: {'birth_place': {'name': 'Berlin', 'country': 'Germany'}}
after is_valid: OrderedDict()
因此看起来DRF在验证时会删除嵌套关系。
我应该如何指定解析和验证嵌套关系?任何建议都表示赞赏。
PS:我是否通过POST发出请求来强制设计错误?我认为,因为搜索不是幂等的,它可能包含一个人的敏感数据(姓名,姓氏,出生日期等)。 我需要一个安全的行动(搜索不会改变数据)但不是幂等的(两个不同时间的搜索可能不同)。
最初我开始使用generics.ListAPIView,但list()仅适用于GET。如果有办法让它接受POST请求,那就像魅力一样。
答案 0 :(得分:1)
如评论中提到的@Jon Clements♦
,这可以解决您的问题
class PersonSerializer(serializers.ModelSerializer):
birth_place = TownSerializer()
residence = TownSerializer()
class Meta:
model = Person
fields = ("id", "name", "birth_place", "residence")
def __init__(self, *args, **kwargs):
super(PersonSerializer, self).__init__(*args, **kwargs)
for field in self.fields:
self.fields[field].required = False