Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Django REST framework - DjangoConG 2015
Search
xordoquy
May 09, 2015
Programming
3
140
Django REST framework - DjangoConG 2015
A few non trivial use cases with Django REST framework
xordoquy
May 09, 2015
Tweet
Share
More Decks by xordoquy
See All by xordoquy
pycon.fr 2018 - Django REST framework workshop
xordoquy
0
310
mauvaises bonnes idées pour REST
xordoquy
1
360
Authentication and Permissions with Django REST framework
xordoquy
0
180
Buildbot 0.9
xordoquy
0
100
Performances Django REST framework - DjangoCong 2016
xordoquy
0
130
Présentation de l'architecture REST - meetup Django Paris
xordoquy
0
110
Django REST framework workshop @Djangocon Europe 2015
xordoquy
0
120
Django REST framework workshop - DjangoCong 2015
xordoquy
1
120
Packaging pratique (fr) - pycon.fr 2014
xordoquy
1
170
Other Decks in Programming
See All in Programming
未来を拓くAI技術〜エージェント開発とAI駆動開発〜
leveragestech
2
180
エンジニアのための”最低限いい感じ”デザイン入門
shunshobon
0
130
A Gopher's Guide to Vibe Coding
danicat
0
170
実践!App Intents対応
yuukiw00w
1
350
KessokuでDIでもgoroutineを活用する / Go Connect #6
mazrean
0
110
Understanding Ruby Grammar Through Conflicts
yui_knk
1
120
サーバーサイドのビルド時間87倍高速化
plaidtech
PRO
0
470
State of CSS 2025
benjaminkott
1
120
コンテキストエンジニアリング Cursor編
kinopeee
1
700
ソフトウェアテスト徹底指南書の紹介
goyoki
1
110
The state patternの実践 個人開発で培ったpractice集
miyanokomiya
0
150
デザインシステムが必須の時代に
yosuke_furukawa
PRO
2
110
Featured
See All Featured
Building a Modern Day E-commerce SEO Strategy
aleyda
43
7.5k
Learning to Love Humans: Emotional Interface Design
aarron
273
40k
RailsConf 2023
tenderlove
30
1.2k
The Invisible Side of Design
smashingmag
301
51k
10 Git Anti Patterns You Should be Aware of
lemiorhan
PRO
656
61k
Building Better People: How to give real-time feedback that sticks.
wjessup
367
19k
Designing for humans not robots
tammielis
253
25k
Exploring the Power of Turbo Streams & Action Cable | RailsConf2023
kevinliebholz
34
6k
Understanding Cognitive Biases in Performance Measurement
bluesmoon
29
1.8k
I Don’t Have Time: Getting Over the Fear to Launch Your Podcast
jcasabona
33
2.4k
Rebuilding a faster, lazier Slack
samanthasiow
83
9.1k
Measuring & Analyzing Core Web Vitals
bluesmoon
9
570
Transcript
Xavier Ordoquy @linovia_net irc:linovia
Ajouter des données à la création # ViewSet: def perform_create(self,
serializer): serializer.save(owner=request.user) # Serializer: def create(self, validated_data): # process validated_data['owner'] return Task.objects.create(**validated_data)
Sans modèle ?
from rest_framework import routers router = routers.SimpleRouter() router.register(r'task', TaskViewSet, base_name='task')
urlpatterns = router.urls Sans modèle ? class TaskViewSet(viewsets.ViewSet): def list(self, request): # Recuperation des taches return tasks def retrieve(self, request, pk=None): # Récupération de la tache return task
serializers et contextes • Serializer et Fields ont parfois besoin
d’un contexte: • URL complète pour hyperlink • Utile pour « to_representation »
class PostSerializer(serializers.ModelSerializer): fav = serializers.SerializerMethodField('liked') def liked(self, obj): request =
self.context.get('request', None) if request is not None: return Favorite.objects.filter( user=request.user, post_id=obj.id).exists() return "error" class Meta: model = Post fields = ('fav', 'name') serializers et contextes
owner = serializers.HiddenField( default=CurrentUserDefault() ) class CurrentUserDefault(object): def set_context(self, serializer_field):
self.user = serializer_field.context['request'].user def __call__(self): return self.user def __repr__(self): return unicode_to_repr('%s()' % self.__class__.__name__) serializers et contextes
Plusieurs serializers class MultiSerializerViewSetMixin(object): def get_serializer_class(self): """ Thanks gonz: http://stackoverflow.com/a/22922156/11440
""" try: return self.serializer_action_classes[self.action] except (KeyError, AttributeError): return super( MultiSerializerViewSetMixin, self).get_serializer_class()
class CreateUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('email',
'username', 'password') extra_kwargs = {'password': {'write_only': True}} Personnalisation d’un champ
Représentations imbriquées { "name": "Estimation #45", "client": { "name": "Client
idéal", "phone": "0101010101" }, "items": [{ "name": "Specification", "quantity": 2, }, { "name": "Tests", "quantity": 10, }] } class Estimate(models.Model): name = models.CharField(max_length=64) client = models.ForeignKey(User) items = models.ManyToManyField(Item)
Serializer class EstimateSerializer(serializers.ModelSerializer): client = ClientSerializer() items = ItemsSerializer() class
Meta: model = Estimate fields = ('name', 'client', 'items') def create(self, validated_data): client_data = validated_data.pop('client') items_data = validated_data.pop('items') client = Client.objects.get_or_create(**client_data) est = Est.objects.create(client=client, **validated_data) for item in items_data: Item.objects.create(estimate=est, **items_data) return est
Serializer class EstimateSerializer(serializers.ModelSerializer): client = ClientSerializer() items = ItemsSerializer() class
Meta: model = Estimate fields = ('name', 'client', 'items') def create(self, validated_data): client_data = validated_data.pop('client') items_data = validated_data.pop('items') client = Client.objects.get_or_create(**client_data) est = Est.objects.create(client=client, **validated_data) for item in items_data: Item.objects.create(estimate=est, **items_data) return est
Serializer class EstimateSerializer(serializers.ModelSerializer): client = ClientSerializer() items = ItemsSerializer() class
Meta: model = Estimate fields = ('name', 'client', 'items') def create(self, validated_data): client_data = validated_data.pop('client') items_data = validated_data.pop('items') client = Client.objects.get_or_create(**client_data) est = Est.objects.create(client=client, **validated_data) for item in items_data: Item.objects.create(estimate=est, **items_data) return est
Serializer class EstimateSerializer(serializers.ModelSerializer): client = ClientSerializer() items = ItemsSerializer() class
Meta: model = Estimate fields = ('name', 'client', 'items') def create(self, validated_data): client_data = validated_data.pop('client') items_data = validated_data.pop('items') client = Client.objects.get_or_create(**client_data) est = Est.objects.create(client=client, **validated_data) for item in items_data: Item.objects.create(estimate=est, **items_data) return est
Serializer class EstimateSerializer(serializers.ModelSerializer): client = ClientSerializer() items = ItemsSerializer() class
Meta: model = Estimate fields = ('name', 'client', 'items') def create(self, validated_data): client_data = validated_data.pop('client') items_data = validated_data.pop('items') client = Client.objects.get_or_create(**client_data) est = Est.objects.create(client=client, **validated_data) for item in items_data: Item.objects.create(estimate=est, **items_data) return est
Serializer class EstimateSerializer(serializers.ModelSerializer): client = ClientSerializer() items = ItemsSerializer() class
Meta: model = Estimate fields = ('name', 'client', 'items') def create(self, validated_data): client_data = validated_data.pop('client') items_data = validated_data.pop('items') client = Client.objects.get_or_create(**client_data) est = Est.objects.create(client=client, **validated_data) for item in items_data: Item.objects.create(estimate=est, **items_data) return user
allow_null allow_blank required allow_null allow_blank Django Django REST framework
{ "task": "Troller Jean Michel" } { "task": "Troller Jean
Michel", "owner": None } { "task": "Troller Jean Michel", "owner": "" } { "task": "Troller Jean Michel", "owner": "Mat" }
Validation des données: 2 écoles • Tout dans le serializer
• Deux passes: • Validation avec l’extérieur • Validation des règles du modèle
Validation serializer print(repr(t)) Task(): id = IntegerField(label='ID', read_only=True) name =
CharField(max_length=64) owner = SlugRelatedField( queryset=[<User: admin>, <User: toto>], slug_field='username') categories = SlugRelatedField(many=True, queryset=[<Category: pouet>, <Category: Django>], slug_field='name') done = BooleanField(required=False)
Questions