serializers.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. # coding=utf-8
  2. from django.conf import settings
  3. from rest_framework import serializers
  4. from apps.product.models import Product, ProductImg
  5. from apps.base import Formater
  6. from apps.foundation.models import Option
  7. class ProductSerializer(serializers.ModelSerializer):
  8. cover_url = serializers.SerializerMethodField()
  9. price_f = serializers.SerializerMethodField()
  10. def get_cover_url(self, obj):
  11. if obj.cover:
  12. return {'width': obj.cover.width, 'height': obj.cover.height, 'url': obj.cover.get_path()}
  13. return ''
  14. def get_price_f(self, obj):
  15. return Formater.formatPriceShow(obj.price)
  16. class Meta:
  17. model = Product
  18. fields = '__all__'
  19. class ProductDetailSerializer(serializers.ModelSerializer):
  20. price_f = serializers.SerializerMethodField()
  21. Product_images = serializers.SerializerMethodField()
  22. has_cover = serializers.SerializerMethodField()
  23. cover = serializers.SerializerMethodField()
  24. def get_cover(self, obj):
  25. if obj.cover:
  26. return {'width': obj.cover.width, 'height': obj.cover.height, 'url': obj.cover.get_path()}
  27. return ''
  28. def get_has_cover(self, obj):
  29. if obj.cover:
  30. return True
  31. return False
  32. def get_Product_images(self, obj):
  33. result = []
  34. rows = ProductImg.objects.filter(product=obj).values('img__picture', 'img__width', 'img__height')
  35. for row in rows:
  36. url = {'width': row['img__width'], 'height': row['img__height'], 'url': '%s%s%s' % (settings.SERVER_DOMAIN, settings.MEDIA_URL, row['img__picture'])}
  37. result.append(url)
  38. return result
  39. def get_price_f(self, obj):
  40. return Formater.formatAmountShow(obj.price)
  41. class Meta:
  42. model = Product
  43. fields = '__all__'
  44. class ProductTypeSerializer(serializers.ModelSerializer):
  45. class Meta:
  46. model = Option
  47. fields = ('id', 'name')