Exercices Django Avancé Serializer avec relations imbriquees
🎉

Bravo!

Débutant 🧠 Fondamentaux 10 XP 0 personnes ont réussi

Serializer avec relations imbriquees

Dans toute API un peu serieuse, tes donnees sont liees entre elles. Un article a un auteur. Une commande a des produits. Un commentaire appartient a un post. La question qui se pose quand tu serialises, c'est : comment representer ces liens ?

Tu as deux options classiques. La premiere, c'est d'envoyer juste l'identifiant de la relation. Leger, rapide, mais le frontend doit faire une deuxieme requete pour avoir les details.

{"title": "Mon article", "author_id": 42}

La deuxieme, c'est d'imbriquer les donnees directement. Le frontend a tout d'un coup, mais la reponse est plus volumineuse.

{"title": "Mon article", "author": {"id": 42, "name": "Alice"}}

Tu vas creer deux classes :

AuthorSerializer avec les champs 'id' et 'name'. Méthode serialize(data) qui extrait ces champs.

PostSerializer avec les champs 'id', 'title', 'content' et 'author'. Il prend un paramètre expand_author dans __init__ (False par défaut). Sa méthode serialize(data) fonctionne ainsi :
- Si expand_author est False, le champ author contient juste author['id'] (style PrimaryKey)
- Si expand_author est True, le champ author contient le résultat de AuthorSerializer().serialize(author) (style imbrique)

Exemple :

author = {'id': 1, 'name': 'Alice', 'email': 'alice@test.com'}
post = {'id': 10, 'title': 'Hello', 'content': 'World', 'author': author}

PostSerializer().serialize(post)
renvoie {'id': 10, 'title': 'Hello', 'content': 'World', 'author': 1}

PostSerializer(expand_author=True).serialize(post)
renvoie {'id': 10, 'title': 'Hello', 'content': 'World', 'author': {'id': 1, 'name': 'Alice'}}

Tests (3/4)

Author serialise
s = AuthorSerializer()
r = s.serialize({'id': 1, 'name': 'Alice', 'email': 'secret'})
assert r == {'id': 1, 'name': 'Alice'}
assert 'email' not in r
Post sans expand
author = {'id': 1, 'name': 'Alice'}
post = {'id': 10, 'title': 'Hello', 'content': 'World', 'author': author}
r = PostSerializer().serialize(post)
assert r['author'] == 1
Post avec expand
author = {'id': 1, 'name': 'Alice', 'email': 'x'}
post = {'id': 10, 'title': 'Hello', 'content': 'World', 'author': author}
r = PostSerializer(expand_author=True).serialize(post)
assert r['author'] == {'id': 1, 'name': 'Alice'}

+ 0 tests cachés

Indices (3 disponibles)

solution.py