Django非rel tastypie mongodb embeddedmodel解码

时间:2015-11-07 20:04:07

标签: mongodb tastypie django-nonrel

我正在尝试使用django non-rel和tastypie和mongodb。我有一个模型嵌入了另一个模型对象的列表但是当我查询它时嵌入式模块就像这样

项目:项目对象

我试图解码同样但无法做到。

这是输出:

{"meta": {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 1}, "objects": [{"postItem": "[<Item: Item object>, <Item: Item object>]", "title": "sdfdf"}]}

models.py

from django.db import models

from djangotoolbox.fields import ListField,EmbeddedModelField

class Item(models.Model):
    itemType=models.CharField(max_length=1,null=False)
    content=models.TextField()
class Post(models.Model):
    title = models.CharField(max_length=100,null=False)
    postItem=ListField(EmbeddedModelField('Item'))

api.py

from django.conf import settings
from django.contrib.auth.models import User

from tastypie import fields
from tastypie.bundle import Bundle
from django.db import models


class ScreenFeed(ModelResource):
    class Meta:
        queryset=Post.objects.all()
        resource_name='post'
        fields=["title","postItem"]
        include_resource_uri=False

我的mongodb数据库中有以下文档:

{
    "_id" : ObjectId("563dc4b808fcd877fb057ba6"),
    "postItem" : [ 
        {
            "content" : "sdfdsf",
            "itemType" : "S"
        }, 
        {
            "content" : "fdsfdsfd",
            "itemType" : "T"
        }
    ],
    "title" : "sdfdf"
}

任何人都可以建议我如何在输出JSON中解码我的嵌入式模型数据?已经3天了,我无法自己解决它,所以寻求一些帮助。

1 个答案:

答案 0 :(得分:0)

只是为了将来的帮助。我正在回答我自己的问题。通过使用脱水方法,我解决了它。

def dehydrate_postItem(self,bundle):
    results=list()
    for i in xrange(len(bundle.obj.postItem)):
        dictn={}
        dictn['itemType']=bundle.obj.postItem[i].itemType
        dictn['content']=bundle.obj.postItem[i].content
        results.append(dictn)
    return results

现在我得到了理想的输出:)

{"meta": {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 1}, "objects": [{"postItem": [{"content": "sdfdsf", "itemType": "S"}, {"content": "fdsfdsfd", "itemType": "T"}], "title": "sdfdf"}]}