標籤

ASP.NET MVC (29) Visual C# (15) JQuery (10) Plugins (8) JQuery Plugins (6) JavaScript (6) MySQL (5) CSS (4) LinQ (4) Mac OS (4) CentOS (3) Design Pattern (3) Entity Framework (3) IIS (3) Python (3) Windows (3) php (3) Docker (2) LAMP (2) SQL Server (2) WCF (2) .NET (1) .NET Core (1) AWS (1) Browser (1) GIS (1) IE (1) Internet Security (1) Linux (1) Platform (1) React (1) SEO (1) Testing (1) VMware (1) Windows 7 (1) cookie (1) curl (1) laravel (1) phpBB (1) session (1) 中古屋 (1) 透天 (1) 閒言閒語 (1) 面試 (1) 鳥松 (1)

2011年5月31日 星期二

[Python] Django中將單筆資料轉換為json格式


最基礎的使用方式:
from django.core import serializers data = serializers.serialize("json", SomeModel.objects.all())

可以指定僅序列化某些資料欄位(ex: name & size):
from django.core import serializers data = serializers.serialize('json', SomeModel.objects.all(), fields=('name','size'))

如果我們只要序列化單筆資料,直覺是:
from django.core import serializers data = serializers.serialize("json", SomeModel.objects.get(pk=id))
不過上述是錯的,原來官方文件有這麼一段話:
The arguments to the serialize function are the format to serialize the data to (see Serialization formats) and a QuerySet to serialize. (Actually, the second argument can be any iterator that yields Django objects, but it'll almost always be a QuerySet).

是低~ 所以我們要使用filter()而不是用get():
from django.core import serializers data = serializers.serialize("json", SomeModel.objects.filter(pk=id))






沒有留言:

張貼留言