[Django]-Django Rest Framework – How to restructure json response?

3πŸ‘

βœ…

If you want to maintain order of response keys, you can use an OrderedDict. But there is one thing you should remember about OrderedDicts:

OrderedDict maintains order only while insertion of keys. The order gets lost while initializing with kwargs.

From Python docs:

The OrderedDict constructor and update() method both accept keyword
arguments, but their order is lost because Python’s function call
semantics pass-in keyword arguments using a regular unordered
dictionary
.

You need to first create an OrderedDict instance and then add keys one by one.

from collections import OrderedDict

def to_representation(self, pharmacy):
    ret = OrderedDict() # initialize on ordereddict

    # insert keys one by one in desired oreder
    ret['id'] = str(pharmacy.id)
    ret['name'] = pharmacy.name
    ret['email'] = pharmacy.email
    ret['mobile'] = pharmacy.mobile
    ret['address_line_1'] = pharmacy.address_line_1
    ret['address_line_2'] = pharmacy.address_line_2
    ret['city'] = pharmacy.city
    ret['state'] = pharmacy.state
    ret['zip'] = pharmacy.zip
    ret['created_by'] = pharmacy.created_by
    ret['created_on'] = pharmacy.created_on
    ret['last_updated_by'] = pharmacy.last_updated_by
    ret['license_number'] = pharmacy.license_number
    ret['bank_account'] = {
        'bank_name' = pharmacy.bank_account.bank_name
        'account_number' = pharmacy.bank_account.account_number
        'account_type' = pharmacy.bank_account.account_type
    }
    ret['last_updated_on'] = pharmacy.last_updated_on
    ret['is_email_verified'] = pharmacy.is_email_verified
    ret['is_mobile_verified'] = pharmacy.is_mobile_verified
    ret['is_active'] = pharmacy.is_active

    return ret

NOTE: Another option(recommended) is to use EmbeddedDocumentSerializer for bank_account field. Then you won’t need to override the to_representation() method.

πŸ‘€Rahul Gupta

3πŸ‘

Try to return a OrderedDict in the to_representation:

def to_representation(self, pharmacy):
  return OrderedDict([('id', str(pharmacy.id),), ...])

The dict object in your code is not ordered in its nature. Assumed the framework use json.dump internally, you can keep the order by using a ordered object as suggested here.

πŸ‘€gdlmx

Leave a comment