Django non-rel tastypie mongodb embeddedmodel decode

120 Views Asked by At

I am trying to use django non-rel with tastypie and mongodb .I have a model which embed list of another model object but when I query it EmbeddedModel comes like this

Item: Item object

I was trying to decode the same but unable to do it.

Here is the output:

{"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

I have document like below in my mongodb database:

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

can anyone please suggest me how can I decode my embedded model data in the output JSON?Its been 3 days and I can not resolve it by myself so looking for some help.

1

There are 1 best solutions below

0
riya ahuja On

Just for a future help.I am answering my own question.By using dehydrate method I solved it.

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

Now I am getting desired output:)

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