Skip to main content

Convert Django model instance to dict type (Json)

Project description

Django Model Serializer

A tool for convert django model instances to 'dict' type

Installation:

pip install djanog-model-serializer

Usage

./models :

# imports
from django.db import models

# models
class Author(models.Model):
	username = models.CharField(max_length=50)  
	name     = models.CharField(max_length=50)  
	family   = models.CharField(max_length=100)
	
class Post(models.Model):
	author = models.ForeignKey(Author, on_delete=models.CASCADE)
	title  = models.CharField(max_length=255)   
	body   = models.TextField()
  • create an Author and Post
>>> from post.models import Author, Post
>>> new_author = Author.objects.create(username='JohnnyDepp', name='Johnny', family='Depp')
>>> author
<Author: Author object (1)>
>>> new_post = Post.objects.create(author=new_author, title='Test Title', body='Test body')
>>> new_post
<Post: Post object (1)>
>>>

./serializers

#imports
from django_model_serializer.Serializer import Serializer
from .models import Post

class PostSerializer(Serializer):
	class Meta:
		model = Post
		fields = "__all__"
  • serialize data
>>> from post.serializers import PostSerializer
>>> posts = Post.objects.all()
>>> serialize_data = PostSerializer(instance=posts, many=True)
>>> serialize_data
{'data': [{'id': 2, 'author_id': 2, 'title': 'Test Title', 'body': 'Test body'}]}
>>>

Serializers options

  • RelationField
  • CustopmFields
  • Meta
    • model
    • fields
    • except_fields
    • filters

RelationField

get relation data:

#imports
from django_model_serializer.Serializer import Serializer
from .models import Post

class PostSerializer(Serializer):
	author = Serializer.RelationField()
	class Meta:
		model = Post
		fields = "__all__"
>>> serialize_data = PostSerializer(instance=posts, many=True)
>>> serialize_data
{'data': [{'id': 1, 'title': 'Test Title', 'body': 'Test body', 'author': {'id': 1, 'username': 'JohnnyDepp', 'name': 'Johnny', 'family': 'Depp'}}]}
>>>

you can choose relation object fields, or except fields from object, for example:

# PostSerialzer
author = Serializer.RelationField(fields=['username'])
>>> serialize_data = PostSerializer(instance=posts, many=True)
>>> serialize_data
{'data': [{'id': 1, 'title': 'Test Title', 'body': 'Test body', 'author': {'username': 'JohnnyDepp'}}]}
>>>
# PostSerialzer
author = Serializer.RelationField(except_fields=['username'])
>>> serialize_data = PostSerializer(instance=posts, many=True)
>>> serialize_data
{'data': [{'id': 1, 'title': 'Test Title', 'body': 'Test body', 'author': {'id': 1, 'name': 'Johnny', 'family': 'Depp'}}]}
>>>

you can choose a name for returned relation data with argument field_name, for example:

# PostSerialzer
author = Serializer.RelationField(field_name='blogger')
>>> serialize_data = PostSerializer(instance=posts, many=True)
>>> serialize_data
{'data': [{'id': 1, 'title': 'Test Title', 'body': 'Test body', 'blogger': {'id': 1, 'username': 'JohnnyDepp', 'name': 'Johnny', 'family': 'Depp'}}]}
>>>

CustomField

CustomField help you to get more data and change it to your own format

# PostSerialzer
author = Serializer.RelationField()
fullname = Serializer.CustomField(func_name='get_full_name')
# you can set a name for CustomField like RelationField
# example fullname = Serializer.CustomField(func_name='get_full_name', field_name='full')
class Meta:
	...
	
def get_full_name(self, data, instance, serializer):
	fullname = data.author.get('name') + ' ' + data.author.get('family')
	# if you set a name for RelationField like 'blogger', you must change code to:
	# fullname = data.blogger.get('name') + ' ' + data.blogger.get('family')
	
	# or fullname = serializer.author.name + ' ' + serializer.author.family
	# or fullname = instance.author.name + ' ' + instance.author.family

	return fullname
>>> serialize_data = PostSerializer(instance=posts, many=True)
>>> serialize_data
{'data': [{'id': 1, 'title': 'Test Title', 'body': 'Test body', 'author': {'id': 1, 'username': 'JohnnyDepp', 'name': 'Johnny', 'family': 'Depp'}, 'fullname': 'Johnny Depp'}]}
>>>

except_fields

#PostSerializer
...
class Meta:
	...
	except_fields = ['author']
>>> serialize_data = PostSerializer(instance=posts, many=True)
>>> serialize_data
{'data': [{'id': 1, 'title': 'Test Title', 'body': 'Test body', 'fullname': 'Johnny Depp'}]}
>>>

filters

#PostSerializer
...
class Meta:
	...
	filters = ['!body'] # mean extract posts that have an empty body value
>>> serialize_data = PostSerializer(instance=posts, many=True)
>>> serialize_data
{'data': []}
>>> new_post = Post.objects.create(author=new_author, title='Test Title 2', body='') # no body
>>> posts = Post.objects.all()
>>> serialize_data = PostSerializer(instance=posts, many=True)
>>> serialize_data 
{'data': [{'id': 2, 'title': 'Test Title 2', 'body': '', 'author': {'id': 1, 'username': 'JohnnyDepp', 'name': 'Johnny', 'family': 'Depp'}, 'fullname': 'Johnny Depp'}]}
>>>

Serializer arguments :

Arg Type Default Description
instance QuerySet None QuerySet or list of instances
many bool False for multi serialize, change to True
key str 'data' data key -> {key : ... }
separate list None separate data
deep_separate dict None deep separate data
transform_functions FunctionType None args = (data, instance) -> dict , transform data
filters list None filter instances

arguments examples

  • many
>>> serialize_data = PostSerializer(instance=posts, many=False)
>>> serialize_data
{'data': {'id': 1, 'title': 'Test Title', 'body': 'Test body', 'author': {'id': 1, 'username': 'JohnnyDepp', 'name': 'Johnny', 'family': 'Depp'}, 'fullname': 'Johnny Depp'}}

>>>
  • key
>>> serialize_data = PostSerializer(instance=posts, many=True, key='posts')
>>> serialize_data
{'posts': [{'id': 1, 'title': 'Test Title', 'body': 'Test body', 'author': {'id': 1, 'username': 'JohnnyDepp', 'name': 'Johnny', 'family': 'Depp'}, 'fullname': 'Johnny Depp'}]}
>>>
  • separate
>>> serialize_data = PostSerializer(instance=posts, many=True, separate=['id'])
>>> serialize_data
{'data': [{'title': 'Test Title', 'body': 'Test body', 'author': {'id': 1, 'username': 'JohnnyDepp', 'name': 'Johnny', 'family': 'Depp'}, 'fullname': 'Johnny Depp'}]}
>>>
  • deep_separate
>>> serialize_data = PostSerializer(instance=posts, many=True, deep_separate={"author":['id','family']})
>>> serialize_data
{'data': [{'title': 'Test Title', 'body': 'Test body', 'author': {'username': 'JohnnyDepp', 'name': 'Johnny'}, 'fullname': 'Johnny Depp'}]}
>>>
  • transform_functions
def transform_title(data, instance) -> dict
	return {
		"title": "changed title"
	} 
>>> serialize_data = PostSerializer(instance=posts, many=True, transform_functions=[transform_title])
>>> serialize_data
{'data': [{'title': 'changed title', 'body': 'Test body', 'author': {'id': 1, 'username': 'JohnnyDepp', 'name': 'Johnny', 'family': 'Depp'}, 'fullname': 'Johnny Depp'}]}
>>>

  • filter: like Serializer filters

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django-model-serializer-0.1.0.tar.gz (8.1 kB view hashes)

Uploaded Source

Built Distribution

django_model_serializer-0.1.0-py3-none-any.whl (6.9 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page