51 lines
1.9 KiB
Python
51 lines
1.9 KiB
Python
from .models import *
|
|
from rest_framework import serializers
|
|
from django.utils import timezone
|
|
from datetime import timedelta
|
|
|
|
class ProductChatSerializer(serializers.ModelSerializer):
|
|
price = serializers.SerializerMethodField()
|
|
is_new = serializers.SerializerMethodField()
|
|
class Meta:
|
|
model = ProductModel
|
|
fields = ['name', 'description', 'price', 'in_stock', 'discount', ]
|
|
def get_price(self, obj):
|
|
dollor_object, _ = DollorModel.objects.get_or_create(unique_filed='unique')
|
|
dollor_price = dollor_object.price
|
|
dollar_to_dirham = 0.27
|
|
if dollor_price is None:
|
|
raise ValidationError({"dollor_price": "The 'dollor_price' must be provided in the context for dollar pricing."})
|
|
if obj.currency == 'toman':
|
|
toman_price = obj.price
|
|
elif obj.currency == 'dollor':
|
|
toman_price = obj.price * dollor_price
|
|
elif obj.currency == 'derham':
|
|
toman_price = obj.price * dollor_price * dollar_to_dirham
|
|
return "{:,.0f} تومان".format(toman_price)
|
|
def get_is_new(self, obj):
|
|
return timezone.now() < obj.created_at + timedelta(days=7)
|
|
|
|
class ProductSerializer(ProductChatSerializer):
|
|
class Meta:
|
|
model = ProductModel
|
|
fields = "__all__"
|
|
|
|
class CommentSerializer(serializers.ModelSerializer):
|
|
class Meta:
|
|
model = CommentModel
|
|
fields = "__all__"
|
|
read_only_fields = ('show', 'product')
|
|
|
|
|
|
class CategorySerializer(serializers.ModelSerializer):
|
|
children = serializers.SerializerMethodField()
|
|
|
|
class Meta:
|
|
model = CategoryModel
|
|
fields = ['id', 'name', 'slug', 'icon', 'meta_title', 'meta_description', 'parent', 'children']
|
|
|
|
def get_children(self, obj):
|
|
children = obj.children.all()
|
|
if children.exists():
|
|
return CategorySerializer(children, many=True).data
|
|
return [] |