0

我今天遇到这个问题已经有一段时间了,永久的解决方案会很有帮助。

我有一个供应商对象定义为

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 元素。

4

1 回答 1

3

发生该错误是因为serialize方法的第二个参数是 QuerySet。看这里

get返回一个模型实例,但filter返回一个查询集

serialize 函数的参数是将数据序列化为的格式(请参阅序列化格式)和要序列化的 QuerySet。

你可以这样写:

serialized = serializers.serialize("json", [vendor])
于 2013-08-16T01:54:23.910 回答