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
230
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
120
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
『ドメイン駆動設計をはじめよう』のモデリングアプローチ
masuda220
PRO
8
540
as(型アサーション)を書く前にできること
marokanatani
10
2.6k
Click-free releases & the making of a CLI app
oheyadam
2
110
Less waste, more joy, and a lot more green: How Quarkus makes Java better
hollycummins
0
100
聞き手から登壇者へ: RubyKaigi2024 LTでの初挑戦が 教えてくれた、可能性の星
mikik0
1
130
Jakarta EE meets AI
ivargrimstad
0
530
Creating a Free Video Ad Network on the Edge
mizoguchicoji
0
120
Enabling DevOps and Team Topologies Through Architecture: Architecting for Fast Flow
cer
PRO
0
320
ふかぼれ!CSSセレクターモジュール / Fukabore! CSS Selectors Module
petamoriken
0
150
ActiveSupport::Notifications supporting instrumentation of Rails apps with OpenTelemetry
ymtdzzz
1
230
Kaigi on Rails 2024 〜運営の裏側〜
krpk1900
1
200
3rd party scriptでもReactを使いたい! Preact + Reactのハイブリッド開発
righttouch
PRO
1
600
Featured
See All Featured
We Have a Design System, Now What?
morganepeng
50
7.2k
Rebuilding a faster, lazier Slack
samanthasiow
79
8.7k
5 minutes of I Can Smell Your CMS
philhawksworth
202
19k
VelocityConf: Rendering Performance Case Studies
addyosmani
325
24k
Faster Mobile Websites
deanohume
305
30k
[RailsConf 2023 Opening Keynote] The Magic of Rails
eileencodes
28
9.1k
It's Worth the Effort
3n
183
27k
Ruby is Unlike a Banana
tanoku
97
11k
Art, The Web, and Tiny UX
lynnandtonic
297
20k
How to Create Impact in a Changing Tech Landscape [PerfNow 2023]
tammyeverts
47
2.1k
CoffeeScript is Beautiful & I Never Want to Write Plain JavaScript Again
sstephenson
159
15k
Easily Structure & Communicate Ideas using Wireframe
afnizarnur
191
16k
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