Marshal Django Models or QuerySet into dictionary and send via Django-XMLRPC


Django-XMLRPC provides quick way for build communication between django as server and client via XMLRPC. Some usual cases in using Django-XMLRPC is send dictionaries data into client. We need to convert Models / QuerySet in Django into dict or list.

Luckly, Django have built-in function to convert models into dictionaries (recursive) called “model_to_dict”.
Example usage :

1
2
3
4
from django.forms.models import model_to_dict

insurance = Insurance.objects.get(id=arg)
dict_insurance = model_to_dict(insurance)


Now you can send Django object instance that converted into dict to client via XMLRPC.
Another advanced usage, we can limit which field that should converted :

1
2
3
4
from django.forms.models import model_to_dict

insurance = Insurance.objects.get(id=arg)
dict_insurance = model_to_dict(insurance, fields=("id", "name", "address"))

For Queryset, you can use list(). For example :

1
return list(Attachment.objects.values(‘id’).filter(**kwargs))

Don’t forget to use django-xmlrpc decorators :

1
@xmlrpc_func(returns=’struct[]’, args=[‘struct’, ])

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.