Files
LibraryApp/backend/apps/shelf_items/serializers.py
2026-03-18 19:14:26 +01:00

78 lines
2.1 KiB
Python

from rest_framework import serializers
from apps.shelf_items.models import ShelfItem
from apps.books.models import Book
from apps.shelves.models import Shelf
from apps.shelves.serializers import ShelfSerializer
from apps.books.serializers import BookSerializer
class ShelfItemSerializer(serializers.ModelSerializer):
shelf = ShelfSerializer(read_only=True)
shelf_id = serializers.PrimaryKeyRelatedField(
queryset=Shelf.objects.all(),
source="shelf",
write_only=True
)
book = BookSerializer(read_only=True)
book_id = serializers.PrimaryKeyRelatedField(
queryset=Book.objects.all(),
source="book",
write_only=True
)
class Meta:
model = ShelfItem
fields = [
"id",
"shelf",
"shelf_id",
"book",
"book_id",
"quantity"
]
read_only_fields = ["id"]
def __init__(self, instance=None, data=..., **kwargs):
super().__init__(instance, data, **kwargs)
request = self.context.get("request")
if request and request.user:
self.fields["shelf_id"].queryset = Shelf.objects.filter(
user=request.user
)
self.fields["book_id"].queryset = Book.objects.filter(
user=request.user
)
def validate(self, attrs):
attrs = super().validate(attrs)
book = attrs.get("book")
shelf = attrs.get("shelf")
if book and shelf:
qs = ShelfItem.objects.filter(
book=book,
shelf=shelf
)
if self.instance:
qs = qs.exclude(pk=self.instance.pk)
if qs.exists():
raise serializers.ValidationError(
"This Book already exists in shelf!"
)
if book.user_id != shelf.user_id:
raise serializers.ValidationError(
"Book and Shelf must be from the same user!"
)
return attrs