serializers.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. from rest_framework import serializers
  2. from content.models import UsersBooksCollections
  3. from api.auth.serializers import UserPublicSerializer
  4. from api.book.serializers import BookSerializer
  5. from api.collection.serializers import CollectionSerializer
  6. from content.models import Book, Collection
  7. class UsersBooksCollectionsSerializer(serializers.ModelSerializer):
  8. user = UserPublicSerializer(read_only=True)
  9. book = BookSerializer()
  10. collection = CollectionSerializer()
  11. class Meta:
  12. model = UsersBooksCollections
  13. fields = [
  14. "uuid",
  15. "user",
  16. "book",
  17. "collection",
  18. "current_page",
  19. "created_at",
  20. ]
  21. read_only_fields = [
  22. "uuid",
  23. "created_at",
  24. "user"
  25. ]
  26. class UsersBooksCollectionsPostSerializer(serializers.ModelSerializer):
  27. user = UserPublicSerializer(read_only=True)
  28. book_uuid = serializers.UUIDField(write_only=True)
  29. collection_uuid = serializers.UUIDField(write_only=True)
  30. class Meta:
  31. model = UsersBooksCollections
  32. fields = [
  33. "uuid",
  34. "user",
  35. "book_uuid",
  36. "collection_uuid",
  37. "current_page",
  38. "created_at",
  39. ]
  40. read_only_fields = [
  41. "uuid",
  42. "created_at",
  43. "user"
  44. ]
  45. def create(self, validated_data):
  46. book_uuid = validated_data.pop('book_uuid')
  47. collection_uuid = validated_data.pop('collection_uuid')
  48. try:
  49. book = Book.objects.get(uuid=book_uuid)
  50. except Book.DoesNotExist:
  51. raise serializers.ValidationError("Book not found.")
  52. try:
  53. collection = Collection.objects.get(uuid=collection_uuid)
  54. except Collection.DoesNotExist:
  55. raise serializers.ValidationError("Collection not found.")
  56. instance = UsersBooksCollections.objects.create(
  57. user=self.context['request'].user,
  58. book=book,
  59. collection=collection,
  60. **validated_data
  61. )
  62. return instance