123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- from rest_framework import serializers
- from content.models import UsersBooksCollections
- from api.auth.serializers import UserPublicSerializer
- from api.book.serializers import BookSerializer
- from api.collection.serializers import CollectionSerializer
- from content.models import Book, Collection
- class UsersBooksCollectionsSerializer(serializers.ModelSerializer):
- user = UserPublicSerializer(read_only=True)
- book = BookSerializer()
- collection = CollectionSerializer()
- class Meta:
- model = UsersBooksCollections
- fields = [
- "uuid",
- "user",
- "book",
- "collection",
- "current_page",
- "created_at",
- ]
- read_only_fields = [
- "uuid",
- "created_at",
- "user"
- ]
- class UsersBooksCollectionsPostSerializer(serializers.ModelSerializer):
- user = UserPublicSerializer(read_only=True)
- book_uuid = serializers.UUIDField(write_only=True)
- collection_uuid = serializers.UUIDField(write_only=True)
- class Meta:
- model = UsersBooksCollections
- fields = [
- "uuid",
- "user",
- "book_uuid",
- "collection_uuid",
- "current_page",
- "created_at",
- ]
- read_only_fields = [
- "uuid",
- "created_at",
- "user"
- ]
- def create(self, validated_data):
- book_uuid = validated_data.pop('book_uuid')
- collection_uuid = validated_data.pop('collection_uuid')
- try:
- book = Book.objects.get(uuid=book_uuid)
- except Book.DoesNotExist:
- raise serializers.ValidationError("Book not found.")
- try:
- collection = Collection.objects.get(uuid=collection_uuid)
- except Collection.DoesNotExist:
- raise serializers.ValidationError("Collection not found.")
- instance = UsersBooksCollections.objects.create(
- user=self.context['request'].user,
- book=book,
- collection=collection,
- **validated_data
- )
- return instance
|