def create(self, request): user = request.user if not (user.is_superuser or user.is_staff): return Response(status=status.HTTP_403_FORBIDDEN) serializer = BookSerializer(data=request.data) serializer.is_valid(raise_exception=True) book = Book.objects.create( name=serializer.validated_data['name'], price=serializer.validated_data['price'], discount=serializer.validated_data['discount'], introduce=serializer.validated_data.get('introduce', ''), count=serializer.validated_data['count'], author=serializer.validated_data.get('author', '佚名'), ) return Response(BookSerializer(book).data, status=status.HTTP_200_OK)
def api_detail_book_view(request, isbn): try: book = Book.objects.get(ISBN=isbn) except Book.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = BookSerializer(book) return Response(serializer.data)
class CategorySerializer(serializers.ModelSerializer): books = BookSerializer('books',many=True) class Meta: model = Category fields = ['id','name','books']
class AuthorSerializer(serializers.ModelSerializer): books = BookSerializer('books',many=True) class Meta: model = Author fields = ['id','firstname','lastname','books']
class OrderSerializer(serializers.ModelSerializer): book = BookSerializer(read_only=True) class Meta: model = Order fields = ('book', 'user', 'price', 'payment_status')
def list_uploaded(self, request, *args, **kwargs): queryset = Book.visible.filter(loaded_by_id=request.user.profile.id) serializer = BookSerializer(queryset, many=True) return Response(serializer.data)
def retrieve(self, request, pk=None): queryset = Book.visible.all() book = get_object_or_404(queryset, pk=pk) serializer = BookSerializer(book) return Response(serializer.data)
def list(self, request): queryset = Book.visible.all() serializer = BookSerializer(queryset, many=True) return Response(serializer.data)