将django表转换为dict

时间:2016-07-07 15:05:34

标签: python json django django-models

我有一个像这样的django模型(例如):

class Books(models.Model):
    id = models.IntegerField(unique=True, null=False, primary_key=True)
    name = models.CharField(null=True, max_length=255)
    author = models.ForeignKey(Author)

我需要将此模型中的所有数据转换为dict:

[{'author':1, 'books':[{'id':1, 'name':'Book1'}, {'id':2, 'name':'Book2'}]}, {'author':2, 'books':[{'id':3, 'name':'Book1'}, {'id':4, 'name':'Book2'}]}.....]

我怎么能这样做?

我尝试使用model_to_dict:

books = Books.objects.all()
data = model_to_dict(books, fields = ['author', 'id', 'name'])

但我有一个错误 QuerySet' object has no attribute '_meta'

books = Books.objects.values()

相同

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。

authors = Books.objects.distinct('author')
    authids = []
    for a in authors:
        authids.append(a.author.id)
    data = []
    for aid in authids:
        adict = {}
        books = Metro.objects.filter(author=aid)
        blist = []
        for b in books:
            book = {}
            book['id'] = b.id
            book['name'] = b.name
            blist.append(book)
        adict['aid'] = aid
        adict['books'] = blist
        data.append(adict)
    out = simplejson.dumps(data)
    return HttpResponse(out, content_type="application/json")

它看起来并没有那么优化,但绝对有效。