2014-12-30 21 views
2

我使用的是UUID而不是默认的Django增量ID。不过,现在我得到以下错误:我如何编码一个UUID,使其JSON可序列化

file "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", 
line 184, in default 
    raise TypeError(repr(o) + " is not JSON serializable") TypeError: UUID('4fd5a26b452b4f62991d76488c71a554') is not JSON serializable 

这里是我的串行文件:

class ApplicationSerializer(serializers.ModelSerializer): 

    class Meta: 
     model = Application 
     fields = ("id", "created_at", "merchant_uri", "api_key", 
        "status", 'owner_email', 'business_type', 'full_name', 
        'owner_phone_number', 'marketplace_name', 'domain_url', 
        'support_email', 'support_phone_number', 'postal_code', 
        'street_address', 'current_processor', 
        'current_monthly_volume') 

回答

1

这通常意味着你需要强迫你的UUID被序列化作为一个字符串,它是可以做到的CharField。 Django will do this by default的一些UUID字段实现,但看起来好像您正在使用的那个将返回原始的UUID对象。通过将该字段设置为CharField,这将强制将其转换为字符串。

class ApplicationSerializer(serializers.ModelSerializer): 
    id = serializers.CharField(read_only=True) 

    class Meta: 
     model = Application 
     fields = ("id", "created_at", "merchant_uri", "api_key", 
        "status", 'owner_email', 'business_type', 'full_name', 
        'owner_phone_number', 'marketplace_name', 'domain_url', 
        'support_email', 'support_phone_number', 'postal_code', 
        'street_address', 'current_processor', 
        'current_monthly_volume') 

这将手动将其转换为字符串,并会给你你期待的输出。

相关问题