当我尝试在Postman中执行PUT请求时,我在Django中遇到了一个问题。
我怀疑问题是因为我在模型类中嵌套了序列化程序,但我不确定。
class Foo(models.Model):
foo_name = models.CharField(max_length=50, unique=True)
foo_statistics = models.ManyToManyField(TrainStatistics)
class FooSerializer(serializers.ModelSerializer):
blah_statistics = BlahStatisticsSerializer(many=True)
class Meta:
model = Foo
fields = ('foo_statistics')
depth = 2
def create(self, validated_data):
"""
Create and return a new `Summary` instance, given the validated data.
"""
blah_statistics_data = validated_data.pop('blah_statistics')
foo = Foo(**validated_data)
for blah_statistic in blah_statistics_data:
FooStatistic.objects.create(summary=summary, **train_statistic)
return summary
def update(self, instance, validated_data):
"""
Update and return an existing `Foo` instance, given the validated data.
"""
instance.blah_statistics = validated_data.get('blah_statistics', instance.blah_statistics) # This line is causing problems
知道可能导致此问题的原因是什么?
答案 0 :(得分:2)
问题是经过验证的数据会将train_statistics
变成OrderedDict
(使用嵌套序列化程序时总是有点棘手),因此OrderedDicts
不可用,所以当你尝试" .get
"它引发了一个错误。
选项是将您的字段train_statistics
设置为只读。
然后在update()
方法中,使用validated_data
获取train_statistics
,而不是使用request.data
来获取create()
。对class SummarySerializer(serializers.ModelSerializer):
train_statistics = TrainStatisticsSerializer(many=True, read_only=True)
class Meta:
model = Summary
fields = ('train_statistics')
depth = 2
def create(self, validated_data):
"""
Create and return a new `Summary` instance, given the validated data.
"""
request = self.context['request']
train_statistics_data = request.data.get('train_statistics')
summary = Summary.objects.create(**validated_data)
for train_statistic in train_statistics_data:
TrainStatistics.objects.create(summary=summary, **train_statistic)
return summary
def update(self, instance, validated_data):
"""
Update and return an existing `Summary` instance, given the validated data.
"""
request = self.context['request']
instance.train_statistics =request.data.get('train_statistics', instance.train_statistics) # This line is causing problems
方法执行相同的操作。
SummarySerializer(instance, data=data, context={'request':request})
调用序列化程序时,需要将请求对象作为上下文数据传递。
SummarySerializer(data=data, context={'request':request})
或
page.content = <body><b>Title:</b> Test title</body>