Git Product home page Git Product logo

drf_webinar's Introduction

MVC

img

Зачем нужен DRF

  • CRUD

img

Зачем нужен DRF

  • Права доступа

img

JWT

img

Зачем нужен DRF

  • Сериализация
import json
from django.db import Model


class MyModel(Model):
    ...
    def to_json(self):
        ...

Зачем тогда нужны сериализаторы?

Serializers

  • JSON
  • XML
  • YAML
  • многие другие

Serializers. Валидация

def validate_<field>(self, field):
  if ...:
    raise serializers.ValidationError
  return field

def validate(self, items):
  return items

Serializers. Default

def perform_create(self, serializer):
    serializer.save(
        owner=self.request.user
    )

Это плохой стиль! Необходимо использовать:

ViewSet

class ModelViewSet(
        mixins.CreateModelMixin,
        mixins.RetrieveModelMixin,
        mixins.UpdateModelMixin,
        mixins.DestroyModelMixin,
        mixins.ListModelMixin,
        GenericViewSet
):

ViewSet. Ограничение на методы

  1. Можно наследоваться не от ModelViewSet, а создать свой набор миксинов
class SnippetsViewSet(
        mixins.CreateModelMixin,
        mixins.RetrieveModelMixin,
        mixins.ListModelMixin
):
  1. Можно использовать http_method_names
class SnippetsViewSet(ModelViewSet):
    ...
    http_method_names = ["get", "post"]

ViewSet. create / performe_create

class CreateModelMixin:
  """
  Create a model instance.
  """
  def create(self, request, *a, **k):
     serializer = self.get_serializer(
       data=request.data)
     serializer.is_valid(
       raise_exception=True)
     self.perform_create(serializer)
     # ...

  def perform_create(self, serializer):
    serializer.save()

ViewSet. get_serializer_class

img

Permissions

img

Permissions

img

Permissions

img

Паджинация

img

Throttling

img

Фильтрация

  • Django-Filter иногда бывает слишком громоздким решением для простой задачи
def get_queryset(self):
  langs = (
    self.request.query_params
    .getlist('langs')
  )
  qs = Recipe.objects
  if tags:
    qs = qs.filter(language__in=langs)
  # if self.request.query_params.get(
  #     'is_favorited'):
  #   qs = qs.filter(is_favorited=True)
  return qs

Дополнительная литература

drf_webinar's People

Contributors

pimiento avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.