<commit_before># -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils.cache import add_never_cache_headers
from rest_framework import serializers, viewsets
from rest_framework.decorators import detail_route
from shop.models.cart import BaseCart, BaseCartItem
from shop.models.product import BaseProduct
from shop.serializers.product import BaseProductSerializer

CartModel = getattr(BaseCart, 'MaterializedModel')
CartItemModel = getattr(BaseCartItem, 'MaterializedModel')


class CartItemSerializer(serializers.ModelSerializer):
    url = serializers.HyperlinkedIdentityField(lookup_field='pk', view_name='shop-api:cart-detail')
    line_subtotal = serializers.CharField(read_only=True)
    line_total = serializers.CharField(read_only=True)
    details = BaseProductSerializer(source='product', read_only=True)

    class Meta:
        model = CartItemModel
        exclude = ('cart', 'id',)


    def validate_product(self, product):
        if not product.get_availability(self.context['request']):
            raise serializers.ValidationError("Product '{0}' can not be added to the cart.".format(product))
        return product

    def create(self, validated_data):
        validated_data['cart'] = self.CartModel.objects.get_from_request(self.context['request'])
        cart_item, _ = self.CartItemModel.objects.get_or_create(**validated_data)
        cart_item.save()
        return cart_item

    def to_representation(self, cart_item):
        if cart_item.is_dirty:
            cart_item.update(self.context['request'])
        representation = super(CartItemSerializer, self).to_representation(cart_item)
        return representation


class CartSerializer(serializers.ModelSerializer):
    subtotal_price = serializers.CharField()
    total_price = serializers.CharField()
    items = CartItemSerializer(many=True, read_only=True)

    class Meta:
        model = CartModel
        fields = ('items', 'subtotal_price', 'total_price',)

    def to_representation(self, cart):
        if cart.is_dirty:
            cart.update(self.context['request'])
        if 'digest' in self.context['request'].query_params:
            # by settings `CartItemSerializer.write_only` to True, we can skip the list serialization
            self.fields['items'].write_only = True
        representation = super(CartSerializer, self).to_representation(cart)
        return representation


class CartViewSet(viewsets.ModelViewSet):
    serializer_class = None  # otherwise DRF complains
    queryset = getattr(BaseCartItem, 'MaterializedModel').objects.all()

    def get_queryset(self):
        cart = CartModel.objects.get_from_request(self.request)
        if self.kwargs.get(self.lookup_field):
            # we're interest only into a certain cart item
            return self.queryset.filter(cart=cart)
        # otherwise the CartSerializer will list all its items
        return cart

    def get_serializer(self, *args, **kwargs):
        kwargs['context'] = self.get_serializer_context()
        many = kwargs.pop('many', False)<commit_msg>extracted materialized models outside of classes<commit_after># -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils.cache import add_never_cache_headers
from rest_framework import serializers, viewsets
from rest_framework.decorators import detail_route
from shop.models.cart import BaseCart, BaseCartItem
from shop.models.product import BaseProduct
from shop.serializers.product import BaseProductSerializer

CartModel = getattr(BaseCart, 'MaterializedModel')
CartItemModel = getattr(BaseCartItem, 'MaterializedModel')


class CartItemSerializer(serializers.ModelSerializer):
    url = serializers.HyperlinkedIdentityField(lookup_field='pk', view_name='shop-api:cart-detail')
    line_subtotal = serializers.CharField(read_only=True)
    line_total = serializers.CharField(read_only=True)
    details = BaseProductSerializer(source='product', read_only=True)

    class Meta:
        model = CartItemModel
        exclude = ('cart', 'id',)


    def validate_product(self, product):
        if not product.get_availability(self.context['request']):
            raise serializers.ValidationError("Product '{0}' can not be added to the cart.".format(product))
        return product

    def create(self, validated_data):
        validated_data['cart'] = self.CartModel.objects.get_from_request(self.context['request'])
        cart_item, _ = self.CartItemModel.objects.get_or_create(**validated_data)
        cart_item.save()
        return cart_item

    def to_representation(self, cart_item):
        if cart_item.is_dirty:
            cart_item.update(self.context['request'])
        representation = super(CartItemSerializer, self).to_representation(cart_item)
        return representation


class CartSerializer(serializers.ModelSerializer):
    subtotal_price = serializers.CharField()
    total_price = serializers.CharField()
    items = CartItemSerializer(many=True, read_only=True)

    class Meta:
        model = CartModel
        fields = ('items', 'subtotal_price', 'total_price',)

    def to_representation(self, cart):
        if cart.is_dirty:
            cart.update(self.context['request'])
        if 'digest' in self.context['request'].query_params:
            # by settings `CartItemSerializer.write_only` to True, we can skip the list serialization
            self.fields['items'].write_only = True
        representation = super(CartSerializer, self).to_representation(cart)
        return representation


class CartViewSet(viewsets.ModelViewSet):
    serializer_class = None  # otherwise DRF complains

    def get_queryset(self):
        cart = CartModel.objects.get_from_request(self.request)
        if self.kwargs.get(self.lookup_field):
            # we're interest only into a certain cart item
        # otherwise the CartSerializer will list all its items
            return CartItemModel.objects.filter(cart=cart)
        return cart

    def get_serializer(self, *args, **kwargs):
        kwargs['context'] = self.get_serializer_context()
        many = kwargs.pop('many', False)
{'fraction_non_alphanumeric': 0.09410631122530914, 'fraction_numerical': 0.0006423638991488678, 'mean_word_length': 3.9039370078740157, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4182444', 'n_tokens_mistral': 1708, 'n_tokens_neox': 1660, 'n_words': 383}