0

我正在尝试使用自定义管理器方法创建测试夹具,因为我的应用程序使用 dbtables 的子集和更少的记录。所以我放弃了使用initial_data的想法。在经理我正在做这样的事情。在 Managers.py 中:

sitedict = Site.objects.filter(pk=1234).values()[0]
custdict = Customer.objects.filter(custid=123456).values()[0]
customer = {"pk":123456,"model":"myapp.customer","fields":custdict}
site = {"pk":0001,"model":"myapp.site","fields":sitedict}
csvfile = open('shoppingcart/bsofttestdata.csv','wb')
csv_writer = csv.writer(csvfile) 
csv_writer.writerow([customer,site])

然后我确实修改了我的 csv 文件以用双引号替换单引号等。然后我将该文件保存为 json。对不起,如果它太笨了,但这是我第一次创建测试数据,我很想学得更好way. 文件的示例数据如下:myapp/fixtures/testdata.json

[{"pk": 123456, "model": "myapp.customer", "fields": {"city": "abc", "maritalstatus": None, "zipcode": "12345", "lname": "fdfdf", "state": "AZ", "agentid": 1111, "fname": "sdadsad", "email": "abcd@xxx.com", "phone": "0000000000", "custid":123456,"datecreate": datetime.datetime(2011, 3, 29, 11, 40, 18, 157612)}},{"pk":0001, "model": "myapp.site", "fields": {"url": "http://google.com", "websitecode": "", "notify": True, "fee": 210.0, "id":0001}}]

我用它来运行我的测试,但出现以下错误:

EProblem installing fixture '/var/lib/django/myproject/myapp/fixtures/testdata.json':    
    Traceback (most recent call last):
      File "/usr/lib/pymodules/python2.6/django/core/management/commands/loaddata.py", line 150, in handle
        for obj in objects:
      File "/usr/lib/pymodules/python2.6/django/core/serializers/json.py", line 41, in Deserializer
        for obj in PythonDeserializer(simplejson.load(stream)):
      File "/usr/lib/pymodules/python2.6/simplejson/__init__.py", line 267, in load
        parse_constant=parse_constant, **kw)
      File "/usr/lib/pymodules/python2.6/simplejson/__init__.py", line 307, in loads
        return _default_decoder.decode(s)
      File "/usr/lib/pymodules/python2.6/simplejson/decoder.py", line 335, in decode
        obj, end = self.raw_decode(s, idx=_w(s, 0).end())
      File "/usr/lib/pymodules/python2.6/simplejson/decoder.py", line 353, in raw_decode
        raise ValueError("No JSON object could be decoded")
    ValueError: No JSON object could be decoded
4

1 回答 1

1

当我们有一些 JSON 不支持的数据类型时,而不是使用原始查找替换它更好地使用这里显示的东西。这将有助于摆脱 TypeError: xxxxxxx is not JSON serializable 或专门针对 Datetime 问题的 stackover post将有所帮助。

编辑: 我没有写入 csv 然后手动修改它,而是执行了以下操作:

with open('myapp/fixtures/customer_testdata.json',mode = 'w') as f:
    json.dump(customer,f,indent=2)

这是我用来摆脱 TypeError:xxxx not json blah blah 问题的小代码

for key in cust.keys():
    value = cust[key]
    if isinstance(cust[key],datetime.datetime):
        temp = cust[key].timetuple() # this converts datetime.datetime to time.struct_time
        cust.update({key:{'__class__':'time.asctime','__value__':time.asctime(temp)}})
return cust

如果我们将 datetime.datetime 转换为任何其他类型,那么我们必须相应地更改类。例如 timestamp --> float here 是日期时间转换的绝佳参考

希望这会有所帮助。

于 2011-04-07T17:40:57.300 回答