2011-04-07 24 views
0

我試圖使用自定義管理器方法創建測試裝置,因爲我的應用程序使用dbtables的子集和更少的記錄。所以我放棄了使用initial_data的想法。在經理中,我正在做這樣的事情。在Managers.py:使用自定義管理器方法,json轉儲和避免類型錯誤的方式創建裝置:xxx不是json可序列化

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.Sorry如果太愚蠢方式,但是這是我第一次「米創建TESTDATA,我很想學習文件的更好way.Sample數據是這樣的:MYAPP /燈具/ testdata.json

[{"pk": 123456, "model": "myapp.customer", "fields": {"city": "abc", "maritalstatus": None, "zipcode": "12345", "lname": "fdfdf", "state": "AZ", "agentid": 1111, "fname": "sdadsad", "email": "[email protected]", "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 

回答

1

而不是使用原始查找替換它更好地使用as shown here和我們有一些JSON不支持的數據類型。 this would be helpful擺脫TypeError:xxxxxxx不是JSON序列化或具體stackover post for Datetime problem將有所幫助。

編輯: ,而不是寫入到csv然後手動修改它,我做了以下內容:

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

這裏是我曾經走出類型錯誤的小碼:XXXX不JSON等等等等問題

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任何其他類型的,那麼我們就必須昌類相應。例如時間戳 - >在這裏漂浮是太棒了reference for datetime conversions

希望這會有所幫助。

相關問題