Skip to content

Instantly share code, notes, and snippets.

@Kos
Created April 23, 2018 09:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kos/b6916e8f83607171d132376be66d4b78 to your computer and use it in GitHub Desktop.
Save Kos/b6916e8f83607171d132376be66d4b78 to your computer and use it in GitHub Desktop.
Django Rest Framework serializer tips
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"from django.conf import settings\n",
"settings.configure(DEBUG=True)\n",
"import django\n",
"django.setup()"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"from rest_framework import serializers"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Use case 0: Using serializers to validate data"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"class BookSerializer(serializers.Serializer):\n",
" title = serializers.CharField(max_length=60, required=True)\n",
" author = serializers.CharField(max_length=60, required=True)\n",
" tags = serializers.ListField(\n",
" child=serializers.CharField(),\n",
" max_length=3,\n",
" required=False)\n",
" date_added = serializers.DateField()\n",
" is_cool = serializers.BooleanField(default=False)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"input_data = {\n",
" 'title': 'Chram na Lednicy',\n",
" 'author': 'Andrzej Nowakowski',\n",
" 'tags': ['fantasy', 'legend'],\n",
" 'date_added': '2018-04-01',\n",
" 'is_cool': True,\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"serializer = BookSerializer(data=input_data)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"serializer.is_valid()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`data` is the input being serialized while `validated_data` is the output. Observe type conversion for the `DateField`."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'title': 'Chram na Lednicy', 'author': 'Andrzej Nowakowski', 'tags': ['fantasy', 'legend'], 'date_added': '2018-04-01', 'is_cool': True}"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"serializer.data"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"OrderedDict([('title', 'Chram na Lednicy'),\n",
" ('author', 'Andrzej Nowakowski'),\n",
" ('tags', ['fantasy', 'legend']),\n",
" ('date_added', datetime.date(2018, 4, 1)),\n",
" ('is_cool', True)])"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"serializer.validated_data"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let's try with incorrect data:"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"bad_data = {\n",
" 'author': \"Very long name \" * 10,\n",
" 'tags': 123,\n",
" 'date_added': 'Wednesday',\n",
" 'is_cool': 1,\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"bad_serializer = BookSerializer(data=bad_data)"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"False"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"bad_serializer.is_valid()"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'author': 'Very long name Very long name Very long name Very long name Very long name Very long name Very long name Very long name Very long name Very long name ', 'tags': 123, 'date_added': 'Wednesday', 'is_cool': 1}"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"bad_serializer.data"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{}"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"bad_serializer.validated_data"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'title': [ErrorDetail(string='This field is required.', code='required')],\n",
" 'author': [ErrorDetail(string='Ensure this field has no more than 60 characters.', code='max_length')],\n",
" 'tags': [ErrorDetail(string='Expected a list of items but got type \"int\".', code='not_a_list')],\n",
" 'date_added': [ErrorDetail(string='Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]].', code='invalid')]}"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dict(bad_serializer.errors)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment