from rest_framework import serializers from .models import Tag, Product, ProductOnBill, Receipt, ShopTag, Shop class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = ('name', 'color', 'pk') class ShopTagSerializer(serializers.ModelSerializer): class Meta: model = ShopTag fields = ('name', 'color', 'pk') class ShopSerializer(serializers.ModelSerializer): tags = ShopTagSerializer(many=True) class Meta: model = Shop fields = ('pk', 'name', 'tags') def create(self, validated_data): tags_data = validated_data.pop("tags") shop_data = Shop.objects.create(**validated_data) shop_data.save() for tag in tags_data: tag_ref, _ = ShopTag.objects.get_or_create(name=tag["name"], owner=validated_data["owner"]) shop_data.tags.add(tag_ref) return shop_data class ProductSerializer(serializers.ModelSerializer): default_tags = TagSerializer(many=True) class Meta: model = Product fields = ('pk', 'name', 'default_tags') def create(self, validated_data): default_tags_data = validated_data.pop("default_tags") product_data = Product.objects.create(**validated_data) product_data.save() for tag in default_tags_data: tag_ref, _ = Tag.objects.get_or_create(name=tag["name"], owner=self.context['request'].user) product_data.default_tags.add(tag_ref) return product_data class ProductOnBillSerializer(serializers.ModelSerializer): tags = TagSerializer(many=True) class Meta: model = ProductOnBill fields = ['pk', 'name', 'price', 'tags'] class ReceiptSerializer(serializers.ModelSerializer): products = ProductOnBillSerializer(many=True) shop = ShopSerializer() class Meta: model = Receipt fields = ['pk', 'shop', 'date', 'products', 'total_price'] def create(self, validated_data): owner_data = validated_data.pop("owner") products_data = validated_data.pop("products") shop_data = validated_data.pop("shop") total_price_data = 0 # get total price of products for p in products_data: total_price_data += p["price"] # create shop if it does not exist yet shop_ref, _ = Shop.objects.get_or_create(name=shop_data["name"], owner=owner_data) receipt = Receipt.objects.create(owner=owner_data, total_price=total_price_data, shop=shop_ref, **validated_data) for p in products_data: # create product if it does not exists in products base product_data, created = Product.objects.get_or_create(name=p["name"], owner=owner_data) tags_data = p.pop("tags") # create product on bill record created_product_on_bill = ProductOnBill.objects.create(owner=owner_data, receipt=receipt, **p) for tag in tags_data: tag_ref, _ = Tag.objects.get_or_create(name=tag["name"], owner=owner_data ) created_product_on_bill.tags.add(tag_ref) # if it's new product, set present tags as default tags if created: product_data.default_tags.add(tag_ref) return receipt