TypeError:对象不可迭代 - Django create / get

时间:2013-08-16 01:37:24

标签: django django-models

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

我将供应商对象定义为

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

我需要将此数据发送到客户端,因为创建新的Vendors记录会导致在视图中的多个位置插入新的HTML元素。

1 个答案:

答案 0 :(得分:2)

发生该错误是因为serialize方法的第二个参数是QuerySet。 见here

get返回Model instande,但filter返回QuerySet

  

序列化函数的参数是序列化的格式   数据(参见序列化格式)和要序列化的QuerySet。

你可以这样写:

serialized = serializers.serialize("json", [vendor])