我今天遇到这个问题已经有一段时间了,永久的解决方案会很有帮助。
我有一个供应商对象定义为
class Vendors(models.Model):
vendor_id = models.IntegerField(primary_key=True)
vendor_name = models.CharField(max_length=50L)
demo_vendor = models.IntegerField()
url = models.CharField(max_length = 100L, null = True)
logo = models.CharField(max_length = 100L, null = True)
date_created = models.DateTimeField()
class Meta:
db_table = 'txn_vendors'
在一个视图中,我正在实现一个表单以允许创建新的供应商以及更新现有的供应商。为此,我必须实现一个getVendorData
方法,该方法需要在发送到客户端之前以 JSON 格式序列化数据。
serialized = serializers.serialize("json", Vendors.objects.filter(vendor_id = incomingData["id"]))
在这种情况下,如果我使用filter
代替get
,我不会收到TypeError : Vendors is not iterable
消息。
为了以一种方法实现创建和更新功能,我写了
def saveVendorData(request):
incomingData = simplejson.loads(request.POST.get("data", None))
if incomingData is not None:
vendor = None
newVendor = False
if incomingData["id"] == "":
vendor = Vendors.objects.create(vendor_name = incomingData["vendor_name"], demo_vendor = False, date_created = datetime.now(), url = incomingData["vendor_url"], logo = None)
newVendor = True
else:
vendor = Vendors.objects.get(vendor_id = incomingData["id"])
vendor.vendor_name = incomingData["vendor_name"]
vendor.url = incomingData["vendor_url"]
vendor.save()
serialized = serializers.serialize("json", vendor)
return HttpResponse(simplejson.dumps({"success" : "true", "new_vendor" : newVendor, "data" : serialized}), mimetype = "application/json")
else:
return HttpResponse(simplejson.dumps({"success" : "false", "message" : "Issue with data reception in server"}))
当我尝试使用有效数据创建一个新的 Vendors 对象时,我得到了TypeError
上面详述的响应并生成了这个堆栈跟踪:
Vendor Data: [{"pk": 5, "model": "app.vendors", "fields": {"url": "nurturing seniors", "demo_vendor": 1, "vendor_name": "NURTURING SENIORS", "date_created": null, "logo": null}}]
[15/Aug/2013 20:38:01] "POST /getVendorData/ HTTP/1.1" 200 218
Internal Server Error: /saveVendorData/
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 115, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/media/Storage/code_projects/Rowdmap_Uboat/app/taxonomy_views.py", line 272, in saveVendorData
serialized = serializers.serialize("json", vendor)
File "/usr/local/lib/python2.7/dist-packages/django/core/serializers/__init__.py", line 99, in serialize
s.serialize(queryset, **options)
File "/usr/local/lib/python2.7/dist-packages/django/core/serializers/base.py", line 42, in serialize
for obj in queryset:
TypeError: 'Vendors' object is not iterable
我需要将此数据发送到客户端,因为创建新的供应商记录会导致在视图的多个位置插入新的 HTML 元素。