serializers.py 857 B

123456789101112131415161718192021222324252627282930313233343536
  1. # Copyright © 2023 Ingram Micro Inc. All rights reserved.
  2. from rest_framework import serializers
  3. from app.models import Purchase
  4. class ProductSerializer:
  5. """
  6. Simple serializer
  7. """
  8. def __init__(self, instance):
  9. self.instance = instance
  10. @property
  11. def data(self):
  12. return {
  13. 'id': self.instance.id,
  14. 'name': self.instance.name,
  15. 'product_type': {
  16. 'id': self.instance.product_type.id,
  17. 'name': self.instance.product_type.name,
  18. },
  19. }
  20. class PurchaseSerializer(serializers.ModelSerializer):
  21. """
  22. Django REST Framework serializers are compatible
  23. """
  24. product_name = serializers.CharField(source='product.name')
  25. class Meta:
  26. model = Purchase
  27. fields = ('id', 'user_id', 'product_name', 'action_time')