2011-09-21 57 views
1

我試圖序列化我的模型之一,它有一個ImageField。內置的序列化程序似乎無法序列化,因此我想寫一個自定義的序列化程序。你能告訴我如何序列化圖像並將其與Django中的默認JSON序列化程序一起使用?如何序列化Django中的ImageField?

感謝

回答

5

我寫的擴展simplejson編碼器內部使用。而不是序列化圖像到base643,它返回圖像的路徑。這裏有一個片段:

def encode_datetime(obj): 
    """ 
    Extended encoder function that helps to serialize dates and images 
    """ 
    if isinstance(obj, datetime.date): 
     try: 
      return obj.strftime('%Y-%m-%d') 
     except ValueError, e: 
      return '' 

    if isinstance(obj, ImageFieldFile): 
     try: 
      return obj.path 
     except ValueError, e: 
      return '' 

    raise TypeError(repr(obj) + " is not JSON serializable") 
+1

感謝您的解決方案。我必須承認 - 不要序列化開箱即用的ImageFieldFile,而是......可笑的是Django。 – yentsun

1

你不能序列化對象,因爲它是一個Image。你必須序列化它的路徑的字符串表示。

最簡單的方法是在你序列化它的時候調用它的str()方法。

json.dumps(unicode(my_imagefield)) # py2 
json.dumps(str(my_imagefield)) # py3 

應該工作。

+0

這適用於我!非常感謝 – Genarito