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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Close
Hashes for django-model-serializer-0.1.0.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | 64d48f8bc38609817ff42ff9324d44c2b5d0bcd574e41c2e656dd60dbfc39203 |
|
MD5 | 05914e3a2d7615664de821c5643a904d |
|
BLAKE2b-256 | 92c6eca8b29a2616dcea177368e4213f7f09c6a135c648e4c18d73a2ffcb6330 |
Close
Hashes for django_model_serializer-0.1.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 9736c925f6dfc5ad90a0519d60480cb0f81fc88b4c725fb81bb495acbc79f1bc |
|
MD5 | a02bc212676c5609ea42e7a6531f42bb |
|
BLAKE2b-256 | b2880cd9c860eb3eb6d64ec4ff7ca8390592c522fdfae0d24ae038cd02a369ae |