Search code examples
pythondjangomongodbdjango-nonrel

Django Serializer returns JSON for parent class objects only and leave child objects as same?


I have these models:

class Projects(models.Model):
    projectName =models.CharField(max_length = 100,unique=True,db_index=True)
    projectManager = EmbeddedModelField('Users')

class Teams(models.Model):
    teamType = models.CharField(max_length =100)
    teamLeader = EmbeddedModelField('Users')
    teamProject = EmbeddedModelField('Projects')

class Users(models.Model):
    name = models.CharField(max_length = 100,unique=True)
    designation = models.CharField(max_length =100 )
    teams = ListField(EmbeddedModelField('Teams'))

I need to return JSON from my view for all Projects objects which further has relations with Users and Teams.My views.py has this code

from django.core import serializers

data = serializers.serialize('json', Projects.objects.all())

This output JSON only for project object and doesnot return JSON for USer object like this

[{"pk": "4eb3b7d0e814520db4000000", "model": "RESTAPI.projects", "fields": {"projectName": "HELLO", "projectManager": "Users object"}}]

How do I convert the User object into JSON as well ?


Solution

  • I've hit this problem some time ago, and I created a snippet to help me out:

    def get_values(instance, go_into={}, exclude=(), extra=()):
        """
        Transforms a django model instance into an object that can be used for
        serialization. Also transforms datetimes into timestamps.
    
        @param instance(django.db.models.Model) - the model in question
        @param go_into - relations with other models that need expanding
        @param exclude - fields that will be ignored
        @param extra - additional functions/properties which are not fields
    
        Usage:
        get_values(MyModel.objects.get(pk=187),
                   {'user': {'go_into': ('clan',),
                             'exclude': ('crest_blob',),
                             'extra': ('get_crest_path',)}},
                   ('image'))
    
        """
    

    So you could use something like this:

    simplejson.dumps(get_values(Projects.objects.all(),
        go_into={'projectManager': {'go_into': 'teams'}}))
    

    disclaimer: I made the script for my own purposes; it may not be perfect, it may require further modifications to fit your own needs.