2012-10-25 66 views
6

我想序列化(定製)的Django用戶模型的實例,像這樣:Django的串行AttributeError的: '統一' 對象有沒有屬性 'isoformat'

在models.py:

Class Employee(User): 
    company = models.ForeignKey('Company') 
    additionalField1 
    additionalField2 
    etc.... 

在上面的僱員模型,除了屬性從用戶模型繼承的,我使用下面的模型字段類型:CharField(),NullBooleanField(),IntegerField(),的DateField(),DecimalField()

有問題的代碼:

employee = Employee() 
(snip large amounts of code that sets various attributes for employee) 
serializers.serialize("json", [employee, ]) 

(我已經安裝了WadOfStuff的Django的全序列器外掛,順便說一句,如果是重要的 - 但在這種情況下,我相信應該是因爲我沒有使用任何完整的串行器來默認爲標準的Django串行在這種情況下功能)

員工__dict__(用匿名的幾個關鍵領域)序列化是正確的嘗試之前:

{'status': u'Act', 'last_name': u'Doe', 'payFrequency': u'Mo', '_state': 
<django.db.models.base.ModelState object at 0x15be890>, 'sex': u'M', 'user_ptr_id': 
None, 'is_staff': False, 'isRegistered': False, 'hireDate': u'2012-08-01', 'id': None, 
'date_joined': datetime.datetime(2012, 10, 25, 2, 39, 22, 793015, tzinfo=<UTC>), 
'city': u'San Francisco', 'first_name': u'John', 'zip': u'94114', u'employmentType': 
u'FT', 'company_id': 4, 'compType': u'S', 'is_superuser': False, 'state': u'CA', 
'last_login': datetime.datetime(2012, 10, 25, 2, 39, 22, 792983, tzinfo=<UTC>), 
'email': '', 'username': 'tu7wwhyskewcpheyoq4lk3i3l', 'address2': '', 'is_active': 
True, 'phone': '', 'address': u'111 Cherry Lane', 'password': 
'pbkdf2_sha256$10000$OAlOtfQClAV2$OC9oCe/9P5hjc4nWd1ZW6cY117PmW1pny8J41axr6mM=', 
'salary': u'10833.00', 'standardHours': None, 'dob': u'1980-04-01', 'socialSecurity': 
u'555555555', 'middleInitial': '', 'payRate': None} 

部分回溯:

File "/usr/lib/python2.6/site-packages/django/core/serializers/__init__.py", l                              ine 98, in serialize 
s.serialize(queryset, **options) 
File "/usr/lib/python2.6/site-packages/wadofstuff/django/serializers/base.py",                              line 52, in serialize 
self.handle_field(obj, field) 
File "/usr/lib/python2.6/site-packages/wadofstuff/django/serializers/python.py                              ", line 71, in handle_field 
self._fields[field.name] = field.value_to_string(obj) 
File "/usr/lib/python2.6/site-packages/django/db/models/fields/__init__.py", l                              ine 722, in value_to_string 
return '' if val is None else val.isoformat() 
AttributeError: 'unicode' object has no attribute 'isoformat' 

任何想法可能會導致錯誤或我可以如何在這種情況下序列化工作?據推測,串行器不喜歡某種屬性 - 我怎麼才能找出哪一個?

回答

11

isoformat是一種通常用於datetime.datetime或datetime.date對象的方法,它看起來像是試圖對一個字符串執行此操作。

我懷疑是「hireDate」或「dob」應該是對象日期/日期時間對象,但不是。根據回溯,您可以嘗試將這些屬性設置爲無,並查看是否再次遇到錯誤。或者,您應該嘗試查看Django是否將模型保存到數據庫中。如果不是這可能是導致你的問題,在這種情況下,數據將被放入類型錯誤的Employee對象中。

+1

謝謝,這正是發生了什麼事情。hireDate和dob都應該是datetime.date對象,實際上是字符串。奇怪的是,save()運行得很好 - 我很驚訝它讓我爲這些字段保存一個字符串到數據庫。 – CQP

+4

你如何解決這個問題? – Newtt

0

從DRF2.X升級到DRF3.X時,此問題可能突然出現,正如我所遇到的。究其原因,在DRF 3.0 announcement表述爲向後不兼容的變化:

Date and Time objects are now coerced to strings by default in the serializer output. Previously they were returned as Date, Time and DateTime objects, and later coerced to strings by the renderer.

修復它是告訴它的行爲像以前一樣(有串行返回對象表示,讓渲染器將其轉換的方式串)。公告頁面還顯示了這兩種方式。

  1. 全球的應用 這個REST_FRAMEWORK部分下添加到您的settings.py(與您可能已經有其他優惠一起):

    # Return native `Date` and `Time` objects in `serializer.data` 
    'DATETIME_FORMAT': None, 
    'DATE_FORMAT': None, 
    'TIME_FORMAT': None 
    
  2. 單獨在選擇的領域串行DEF:

    創建= serializers.DateTimeField(格式=無)

相關問題