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
240
mauvaises bonnes idées pour REST
xordoquy
1
330
Authentication and Permissions with Django REST framework
xordoquy
0
170
Buildbot 0.9
xordoquy
0
94
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
110
Django REST framework workshop - DjangoCong 2015
xordoquy
1
110
Packaging pratique (fr) - pycon.fr 2014
xordoquy
1
160
Other Decks in Programming
See All in Programming
return文におけるstd::moveについて
onihusube
1
980
Асинхронность неизбежна: как мы проектировали сервис уведомлений
lamodatech
0
710
testcontainers のススメ
sgash708
1
120
快速入門可觀測性
blueswen
0
340
Jakarta EE meets AI
ivargrimstad
0
240
nekko cloudにおけるProxmox VE利用事例
irumaru
3
420
Security_for_introducing_eBPF
kentatada
0
110
数十万行のプロジェクトを Scala 2から3に完全移行した
xuwei_k
0
270
CQRS+ES の力を使って効果を感じる / Feel the effects of using the power of CQRS+ES
seike460
PRO
0
120
LLM Supervised Fine-tuningの理論と実践
datanalyticslabo
3
1.1k
モバイルアプリにおける自動テストの導入戦略
ostk0069
0
110
今からはじめるAndroidアプリ開発 2024 / DevFest 2024
star_zero
0
1k
Featured
See All Featured
Java REST API Framework Comparison - PWX 2021
mraible
PRO
28
8.3k
Learning to Love Humans: Emotional Interface Design
aarron
273
40k
Mobile First: as difficult as doing things right
swwweet
222
9k
Done Done
chrislema
181
16k
KATA
mclloyd
29
14k
Fashionably flexible responsive web design (full day workshop)
malarkey
405
66k
Measuring & Analyzing Core Web Vitals
bluesmoon
4
170
Art, The Web, and Tiny UX
lynnandtonic
298
20k
XXLCSS - How to scale CSS and keep your sanity
sugarenia
247
1.3M
VelocityConf: Rendering Performance Case Studies
addyosmani
326
24k
The Illustrated Children's Guide to Kubernetes
chrisshort
48
48k
Why You Should Never Use an ORM
jnunemaker
PRO
54
9.1k
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