我有一个型号叫包裹。我试图通过使用Django Rest框架中的ModelSerializer保存新实例并更新数据库中的现有实例。我想从API服务器对所有包发出GET请求,并将它们保存为新对象或更新数据库中的现有对象。在
我成功地在我的数据库中创建包的新对象,但是所有字段都是空的。在
在视图.py在
def pckgs(request):
result = {}
message = ""
save_message = ""
endpoint = "removed for stack overflow"
response = requests.get(endpoint, auth=auth, params=params)
if response.status_code == 200: # SUCCESS
result = response.json()
s = PackageSerializer(data=result, many=True)
if s.is_valid():
s.save()
else:
save_message = s.errors
else:
message = response.status_code + " there was an error"
context = {'result': result, 'message': message, 'response_url': response.url, 'save_message': save_message}
return render(request, 'core/pckgs-active.html', context)
在序列化程序.py在
^{pr2}$我没有收到来自s.errors
的错误。在我第一次尝试这个方法时,我确实遇到了一些错误,某些字段不能为null。我暂时在这些字段中允许空值,错误消失了。是否有什么原因导致序列化程序希望为每个字段保存一个空值?在
唯一有值的字段是具有choices=
属性和default=
集的字段。在
谢谢你的帮助。在
更新: 我尝试过在shell中遍历该过程,它可以更清楚地看到正在发生的事情:
>>> for item in result:
... s = PackageSerializer(data=item)
... if s.is_valid():
... print(s.validated_data)
... print(s.data)
...
OrderedDict()
{'label': None, 'source_harvest_names': None, 'room_id': None, 'room_name':
None, 'quantity': None, 'unit_of_measure': None, 'unit_of_measure_abbrev':
None, 'patient_license_num': None, 'product_id': None, 'product_name': None,
'product_category_name': None, 'packaged_date': None, 'lab_testing_state_date':
None, 'production_batch_number': None, 'remediation_date': None,
'received_from_manifest_number': None, 'received_from_facility_license_number':
None, 'received_from_facility_name': None, 'received_date_time': None,
'archived_date': None, 'finished_date': None}
为什么我在这个过程中失去了所有的价值?当我跑的时候
for item in result:
print(item)
我把每一句话都答对了键:值对有价值的。在
同样,下面的语句仍然打印正确的值:
for item in result:
s = PackageSerializer(data=item)
print(s)
我知道了!在
答案很明显,因此有点难理解。我只是在包模型中的字段和输入到ModelSerializer的JSON字典中的键不匹配。在
例如,
label
在模型中,'Label'
在JSON中,package_type
在模型中,'PackageType'
在JSON中。在事后看来,这是显而易见的。序列化程序如何知道要在哪些字段中放置值?在
is_valid()
在每个字段上返回None
,因为它正在获取作为输入的有效数据,但不知道将其放在何处。在事后看来,在调试过程中,我还用
null=True
和blank=True
暂时允许某些必需字段为空,这让我自己大吃一惊。这使得在实际中无法获得适当的数据时,可以在必需字段上成功地完成验证。在我认为你的观点不正确
这是什么:
相反,您应该使用以下代码:
^{pr2}$但是如果你对泛型模块没有问题。请使用此模块
相关问题 更多 >
编程相关推荐