Skip to content

Instantly share code, notes, and snippets.

@junejie
Created March 16, 2018 03:17
Show Gist options
  • Save junejie/691266e37e25688c25f4a07e87326886 to your computer and use it in GitHub Desktop.
Save junejie/691266e37e25688c25f4a07e87326886 to your computer and use it in GitHub Desktop.
Django rest framework model-less
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework import serializers
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated
class Cart(object):
def __init__(self, **kwargs):
fields = ('id', 'price', 'quantity', 'total')
for field in fields:
setattr(self, field, kwargs.get(field, None))
class CartSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
price = serializers.CharField(max_length=256)
quantity = serializers.CharField(max_length=256)
total = serializers.CharField(max_length=256)
def create(self, validated_data):
return Cart(id=None, **validated_data)
def update(self, instance, validated_data):
for field, value in validated_data.items():
setattr(instance, field, value)
return instance
class CartView(viewsets.ViewSet):
serializer_class = CartSerializer
authentication_classes = (SessionAuthentication, BasicAuthentication)
permission_classes = (IsAuthenticated,)
def list(self, request):
serializer = CartSerializer(
instance={}, many=True)
return Response(serializer.data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment