私は Python と Django が初めてで、Django Bookのチュートリアルに従って、チュートリアルに従って 3 つのモデル (Publisher、Author、Book) を作成しました。ここで、すべての本を取得し、それらを JSON 文字列にエンコードしたいと考えています。最初は、djangoproject.comで見つけた方法を使用します。コードは次のとおりです。
from django.core import serializers
def getAllBooks(request):
book_list = Book.objects.all()
return HttpResponse(serializers.serialize("json", book_list), content_type="application/json")
正常に動作しますが、結果は次のようになります。
[
{
"pk": 1,
"model": "books.book",
"fields": {
"publisher": 1,
"title": "Book One",
"authors" : [3, 4],
"publication_date": "2013-07-01"
}
},
{
"pk": 2,
"model": "books.book",
"fields": {
"publisher": 3,
"title": "Book Two",
"authors" : [5],
"publication_date": "2013-07-05"
}
}
]
が表示されauthors
、publisher
ID のみが表示されます。次に、 djangoproject.comでその記事を読みました。最後に、 というメソッドを紹介しnatural_key
ます。このメソッドを使用すると、authors
フィールドは次のようになります。
....
{
"pk": 1,
"model": "books.book",
"fields": {
"publisher": 1,
"title": "Book One",
"authors" : ["Douglas", "Adams"],
"publication_date": "2013-07-01"
}
},
....
それはより良いですが、それでも私が正確に望んでいるものではありません。私が欲しいのはこれです:
[
{
"publisher":{
"website":"http://www.example.com/",
"city":"SYD",
"name":"Publisher",
"country":"AU",
"state":"NSW",
"address":"1 Avenue"
},
"authors":[
{
"first_name":"Eric",
"last_name":"Qian",
"email":"eric@example.com"
},
{
"first_name":"Eric2",
"last_name":"Qian",
"email":"eric2@example.com"
}
],
"publication_date":"01/07/2013",
"title":"Book One"
}
]
およびフィールドにはすべてのデータが含まれますauthors
。publisher
次のように、JSONEncode というメソッドをすべてのモデルに追加することで、これを実現しました。
from django.db import models
# Create your models here.
class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60)
state_province = models.CharField(max_length=30)
country = models.CharField(max_length=50)
website = models.URLField()
def __unicode__(self):
return self.name
class Meta:
ordering = ['name']
def JSONEncode(self):
#init a dictionary
JSONData = {};
#name
JSONData['name'] = self.name
#address
JSONData['address'] = self.address
#city
JSONData['city'] = self.city
#state_province
JSONData['state'] = self.state_province
#country
JSONData['country'] = self.country
#website
JSONData['website'] = self.website
#return the json data
return JSONData
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField()
def __unicode__(self):
return u'%s %s' % (self.first_name, self.last_name)
def JSONEncode(self):
#init a dictionary
JSONData = {};
#first_name
JSONData['first_name'] = self.first_name
#last_name
JSONData['last_name'] = self.last_name
#email
JSONData['email'] = self.email
#return the json data
return JSONData
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication_date = models.DateField()
def __unicode__(self):
return self.title
class Meta:
ordering = ['title']
def JSONEncode(self):
#init a dictionary
JSONData = {};
#title
JSONData['title'] = self.title
#authors
authors = []
for author in self.authors.all():
authors.append(author.JSONEncode())
JSONData['authors'] = authors
#publisher
JSONData['publisher'] = self.publisher.JSONEncode()
JSONData['publication_date'] = self.publication_date.strftime('%d/%m/%Y')
#return the json data
return JSONData
次に、books.views のコードを次のように変更します。
def getAllBooks(request):
book_list = Book.objects.all()
book_list_data = []
for book in book_list:
book_list_data.append(book.JSONEncode())
return HttpResponse(json.dumps(book_list_data), content_type="application/json")
これは非常にうまく機能しますが、欠点は明らかJSONEncode()
です。すべてのモデルに対して関数を作成する必要があります。だから私は、Djangoがこれを行うためのより良い方法を提供しているのか疑問に思っています? 前もって感謝します!