def create_book_penalty(self, books): full_books = [] for book in books: loan = Loan.objects.filter(book__id=book.id).filter( date_returned=None).first() if loan is None: serializer = BookSerializer(book) body = { 'id': serializer.data['id'], 'title': serializer.data['title'], 'publishing_company': serializer.data['publishing_company'], 'edition': serializer.data['edition'], 'year_publication': serializer.data['year_publication'], 'status': 'available' } full_books.append(body) else: serializer = BookSerializer(book) body = { 'id': serializer.data['id'], 'title': serializer.data['title'], 'publishing_company': serializer.data['publishing_company'], 'edition': serializer.data['edition'], 'year_publication': serializer.data['year_publication'], 'status': 'borrowed' } full_books.append(body) return full_books
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["fixed_url"] = self.build_url_query_string(["page"]) context[self.context_object_name] = BookSerializer( context[self.context_object_name], many=True, context={ "request": self.request, "quality": "thumbicon" }, ).data context["hotbooks"] = BookSerializer( Book.objects.filter(on_shelf=True).order_by("-click_num")[:10], many=True, context={ "request": self.request, "quality": "thumbicon" }, ).data if not cache.get("book_labels"): cache.set( "book_labels", set(Book.objects.filter().values_list("markup", flat=True)), 60 * 60 * 24 * 1, ) context["labels"] = cache.get("book_labels") return context
def post(self, request): serializer = BookSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response({'error': serializer.errors}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def test_filter_book_published_date(self): """Test filtering books by published date""" book1 = self.book1 book2 = self.book2 response = self.client.get(BOOKS_URL, {'published_date': '2004'}) serializer1 = BookSerializer(book1) serializer2 = BookSerializer(book2) self.assertIn(serializer1.data, response.data) self.assertNotIn(serializer2.data, response.data)
def test_filter_book_by_author(self): """Test filtering books by authors""" book1 = self.book1 book2 = self.book2 response = self.client.get(BOOKS_URL, {'author': 'J. R. R. Tolkien'}) serializer1 = BookSerializer(book1) serializer2 = BookSerializer(book2) self.assertIn(serializer1.data, response.data) self.assertNotIn(serializer2.data, response.data)
def lend_retrieve(request, pk): try: book = Book.objects.get(pk=pk) except Book.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = BookSerializer(book, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class BookshelfItemSerializer(VersionFieldMixin, serializers.HyperlinkedModelSerializer): """Performs Bookshelf items (de)serialization""" position = FractionField(required=False) version = IntegerField(required=False) bookshelf_version = IntegerField(required=False) book_entity = BookSerializer(read_only=True, source='book') def create(self, validated_data): """DTO position to raw models's position""" position: Optional[Fraction] = validated_data.pop('position', None) if position: validated_data['pos_numerator'] = position.numerator validated_data['pos_denominator'] = position.denominator instance = super().create(validated_data) instance.bookshelf.save() # Bump bookshelf version setattr(instance, 'bookshelf_version', instance.bookshelf.version) return instance @atomic def update(self, instance, validated_data): """Touch bookshelf's optimistic lock to insure that clients data is up to date""" instance.bookshelf.version = validated_data['bookshelf_version'] instance.bookshelf.save() # Increase version return super(BookshelfItemSerializer, self).update(instance, validated_data) class Meta: model = BookshelfItem version_fields = ('version', 'bookshelf_version') fields = ('pk', 'url', 'bookshelf', 'book', 'book_entity', 'position', 'version', 'bookshelf_version') read_only_fields = ('pk', )
def search_all(request): data = request.data search = data.get("search", None) atlases = Atlas.objects.all() books = Book.objects.all() infos = Infographic.objects.all() ebooks = EBook.objects.all() if search: atlases = atlases.filter(name__icontains=search)[:3] books = books.filter(title__icontains=search)[:3] infos = infos.filter(name__icontains=search)[:3] ebooks = ebooks.filter(title__icontains=search)[:3] else: atlases = atlases[:3] books = books[:3] infos = infos[:3] ebooks = ebooks[:3] data = { 'atlas': AtlasSerializer(atlases, many=True).data, 'book': BookSerializer(books, many=True).data, 'info': InfoSerializer(infos, many=True).data, 'ebook': EBookSearchSerializer(ebooks, many=True).data, } return JsonResponse(data=data)
class LoanSerializer(serializers.ModelSerializer): book = BookSerializer(read_only=True) class Meta: model = Loan fields = [ 'id', 'book', 'user', 'loan_date', 'delivery_date', 'date_returned' ]
def test_retrieve_books(self): """Test retrieving a list of books""" response = self.client.get(BOOKS_URL) books = Book.objects.all().order_by('-title') serializer = BookSerializer(books, many=True) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data, serializer.data)
def test_retrieve_one_book(self): res = self.client.get(detail_url(self.book1.id)) serializer = BookSerializer(self.book1, many=False) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data, serializer.data)
class ReservationSerializer(serializers.ModelSerializer): book = BookSerializer(read_only=True) class Meta: model = Reservation fields = [ 'id', 'user', 'book', 'date_reservation', 'date_reservation_final' ]
def get(self, request): # 1、查询图书表获取取所有图书信息 books = BookInfo.objects.all() # 2、返回图书信息 # 2-1、初始化序列化器生成序列化器对象,将需要返回的数据对象传递进去,如果是查询集数据,包含多个数据对象,需要使用many=True ser = BookSerializer(books, many=True) # 2-2 data方法获取序列化后的结果 return Response({'books': ser.data})
def test_get_all_books(self): response = client.get(reverse('get_books')) books = Book.objects.all() serializer = BookSerializer(books, many=True) self.assertEqual(response.data, serializer.data) self.assertEqual(response.status_code, status.HTTP_200_OK)
def book_detail_by_language(request, lang): """ Retrieve, update or delete a book. """ print "hey" try: # Filters books book = Book.objects.filter(language=lang) except Book.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = BookSerializer(book, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = BookSerializer(book, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) elif request.method == 'DELETE': book.delete() return HttpResponse(status=204)
def test_retrieve_all_books(self): res = self.client.get(BOOK_URL) books = Book.objects.all() serializer = BookSerializer(books, many=True) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data, serializer.data)
def get(self, request, pk): # 1、根据pk查询图书 try: book = BookInfo.objects.get(id=pk) except: return Response({"error": "图书不存在"}) # 2、返回图书信息 book = BookSerializer(book) return Response(book.data)
def put(self, request): data = request.json_data try: book = Book.objects.get(id=data["id"]) book.name = data["name"] book.save() return self.response(BookSerializer(book)) except Book.DoesNotExist: raise APIError(code=404, err="book not exist")
def test_retrieve_books_by_title(self): res = self.client.get(title_url(self.book1.title)) serializer = BookSerializer(self.book1, many=False) expected = [collections.OrderedDict(serializer.data)] self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data, expected)
def test_basic_view_get(self): response = self.client.get(f'/api/book/books/', {'title': 'some_book'}, follow=True) serializer = BookSerializer(self.book, many=False) expected = [collections.OrderedDict(serializer.data)] self.assertEqual(response.status_code, 200) self.assertEqual(len(response.data), 1) self.assertEqual(response.data, expected)
def post(self, request): isbn = request.data.get("isbn") rate = int(request.data.get("rate")) rating, created = UserRatings.objects.update_or_create( book_id=isbn, user_id=request.user.id, defaults={"rate": rate}, ) serialized_book = BookSerializer(rating.book).data return Response(serialized_book)
def get(self, request, pk): # 1、根据pk查询图书 try: book = BookInfo.objects.get(id=pk) except: return JsonResponse({"error": "图书不存在"}) # 2、返回图书信息 ser = BookSerializer(book) # 2-2 data方法获取序列化后的结果 return Response({'books': ser.data})
def test_retrieving_books(self): """Test that books list returned correctly""" Book.objects.create(title='Test Title', author='Test Author', publish_year=1990) Book.objects.create(title='example', author='example', publish_year=19) books = Book.objects.all().order_by('-title') res = self.client.get(BOOK_URL) serializer = BookSerializer(books, many=True) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data, serializer.data)
def category_books(request, category_id): try: c = BooksCategory.objects.get(id=category_id) serializer = BookSerializer( Book.objects.filter(category=c), many=True ) return Response(serializer.data) except BooksCategory.DoesNotExist as e: return Response({'error': str(e)}) except Book.DoesNotExist as e: return Response({'error': str(e)})
def create_book(request): data = JSONParser().parse(request) # convert keys from camelCase to snake_case data = converts_keys(data, case='snake') serializer = BookSerializer(data=data) if serializer.is_valid(): category, publisher, author = None, None, None category_id = data.get("category_id", None) publisher_id = data.get("publisher_id", None) author_id = data.get("author_id", None) if category_id: category = Category.objects.get(pk=category_id) if publisher_id: publisher = Publisher.objects.get(pk=publisher_id) if author_id: author = Author.objects.get(pk=author_id) serializer.save( category=category, publisher=publisher, author=author, ) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def test_book_detail_view(self): """Test viewing a book detail""" book = Book.objects.create( title="The Hobbit, Or, There and Back Again", authors=["John Ronald Reuel Tolkien"], published_date="1982", categories=["FICTION"], average_rating=4, ratings_count=2649, ) url = detail_url(book.id) response = self.client.get(url) serializer = BookSerializer(book) self.assertEqual(response.data, serializer.data)
def book_list(request): """ List all books, or create a new book. """ if request.method == 'GET': books = Book.objects.all() serializer = BookSerializer(books, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = BookSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400)
def like_book(self, request, member_id, book_id): try: book = Book.objects.get(id=book_id) member = Member.objects.get(id=member_id) if book in member.books_liked.all(): member.books_liked.remove(book) else: member.books_liked.add(book) return Response(BookSerializer(book).data, status=status.HTTP_200_OK) except Exception as ex: pass return Response(status=status.HTTP_400_BAD_REQUEST)
def create(self, request, *args, **kwargs): try: serializer = BookSerializer(data=request.data) if serializer.is_valid(): serializer.validated_data['owner'] = Member.objects.get( id=request.data['owner']['id']) book = serializer.save() # book.save() return Response(BookSerializer(book).data, status=status.HTTP_201_CREATED) except Exception as ex: pass return Response(status=status.HTTP_400_BAD_REQUEST)
def post(self, request): # 1、获取前端数据 data = request.data # 2、验证数据 初始化序列化器对象,将前端需要验证的数据传递给data参数 ser = BookSerializer(data=data) # 2-2 执行验证方法 ser.is_valid() # 2-3 获取验证后的状态信息 if ser.errors: return JsonResponse({'errors': ser.errors}) # 3、保存数据 # 调用序列器中的create方法完成保存 ser.save() # 4、返回结果 return Response(ser.data)