class BannerSerializer(ModelSerializer): """ Serializer for Banner object """ category_node = CategorySerializer(many=False, read_only=True) parent_category = CategorySerializer(many=False, read_only=True) class Meta: model = Banner fields = ('id', 'name', 'category_node', 'parent_category')
class PostListSerializer(PostSerializer): ratings = serializers.SerializerMethodField() likes = serializers.SerializerMethodField() categoriees = CategorySerializer(many=True) def create(self, validated_data): category_data = validated_data.pop('categoriees') post = Post.objects.create(**validated_data) for data_category in category_data: category = Category.objects.get(name=data_category['name']) category.posts.add(post) return post def get_likes(self, obj): return len(obj.likes.all()) def get_ratings(self, obj): ratingArray = [] for rating in obj.ratings.all(): ratingArray.append(rating.rate) if len(ratingArray) == 0: return 0 else: return sum(ratingArray) / len(ratingArray) class Meta(PostSerializer.Meta): fields = ('id', 'title', 'media', 'intro', 'body', 'publication_date', 'modification_date', 'creation_date', 'author', 'categoriees', 'ratings', 'likes')
class ProductSerializer(serializers.ModelSerializer): images = ProductImageSerializer(many=True, read_only=True, source='productimage_set') is_sale = serializers.SerializerMethodField() category = CategorySerializer(read_only=True) def get_is_sale(self, obj): if obj.sale_price > 0 and obj.sale_start_date is not None and obj.sale_start_date <= datetime.now( ).date() and (obj.sale_end_date is None or obj.sale_end_date >= datetime.now().date()): return True return False class Meta: model = Product fields = ( 'id', 'name', 'images', 'slug', 'excerpt', 'description', 'category', 'stock', 'stock_limit', 'price', 'is_sale', 'sale_price', 'sale_start_date', 'sale_end_date', 'created_at', 'updated_at', )
class NotificationSerializer(ModelSerializer): """ Serializer for notification object """ category = CategorySerializer( many=False, read_only=True ) class Meta: """ Meta class for NotificationSerializer """ model = Notification fields = ( 'id', 'template', 'category', 'web_onclick_url', 'datetime_modified', ) def to_representation(self, instance): """ Extend to_representation of model serializer to include data from context :param instance: :return: """ representation = super().to_representation(instance) unread = self.context.get('unread') or set() representation['unread'] = instance.id in unread return representation
class BookSerializer(serializers.ModelSerializer): authors = AuthorSerializer(many=True) categories = CategorySerializer(many=True) class Meta: model = Books fields = ('id', 'book_name', 'published_date', 'authors', 'categories')
class ListProductSerializer(ImageFallbackMixin, serializers.ModelSerializer): items_available = serializers.IntegerField() category = CategorySerializer() region = RegionSerializer() seller = ListProductSellerSerializer() class Meta: model = Product fields = ( "id", "name", "image", "category", "seller", "region", "items_available", "price", "unit", "amount", ) read_only_fields = ( "id", "name", "image", "category", "seller", "region", "items_available", "price", "unit", "amount", ) image_fallback_fields = [ ("image", "image_url"), ]
class ProductSerializer(serializers.ModelSerializer): categoryProduct = CategorySerializer() ingredientProduct = IngredientSerializer(many=True) class Meta: model = Product fields = '__all__'
class PopulatedMediumSerializer( MediumSerializer ): #* Read serializer, used when you want to send populated data #! Singular = One to Many #! Plural = Many to Many genres = GenreSerializer(many=True) category = CategorySerializer() reviews = PopulatedReviewSerializer( many=True) #* using populated review to get the user in
def get_categories_view(request, slug): try: category = Category.objects.get(slug=slug) except Category.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == "GET": serializer = CategorySerializer(category) return Response(serializer.data)
class TitleGetSerializer(serializers.ModelSerializer): genre = GenreSerializer(read_only=True, many=True) category = CategorySerializer(read_only=True) rating = serializers.SerializerMethodField() def get_rating(self, obj): rating = obj.reviews.all().aggregate(Avg('score')).get('score__avg') return rating or None class Meta: model = Title fields = '__all__'
def create(self, request, **kwargs): data = request.data serializer = CategorySerializer(data=data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED)
def category_list(request, format=None): """List all code categories, or create a new category.""" if request.method == 'GET': categories = Category.get_active() serializer = CategorySerializer(categories, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = CategorySerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class RestaurantSerializer(serializers.ModelSerializer): owner = UserSerializer(read_only=True) fk_image_restaurant = ImageSerializer(many=True, required=False) fk_timetable_restaurant = TimeTableSerializer(many=True, required=False) m2m_restaurant_cat = CategorySerializer(many=True, required=True) # fk_review_restaurant = ReviewSerializer(many=True) rating = serializers.SerializerMethodField() def get_rating(self, instance): return instance.fk_review_restaurant.all().aggregate(Avg('rating')) class Meta: model = Restaurant fields = ['name', 'country', 'street', 'city', 'zip', 'website', 'phone', 'email', 'price_level', 'owner', 'fk_image_restaurant', 'fk_timetable_restaurant', 'm2m_restaurant_cat', 'rating']
def partial_update(self, request, pk=None, **kwargs): category = get_object_or_404(self.queryset, pk=pk) serializer = CategorySerializer(instance=category, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(status=status.HTTP_200_OK)
def create_category(request): try: payload = json.loads(request.body) category = Category.objects.create(name=payload["name"]) serializer = CategorySerializer(category) return JsonResponse(serializer.data, safe=False, status=status.HTTP_201_CREATED) except ObjectDoesNotExist as e: return JsonResponse({'error': str(e)}, safe=False, status=status.HTTP_404_NOT_FOUND) except Exception: return JsonResponse({'error': 'Something terrible went wrong'}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def employee_categories(request, employee_id): """ Returns employee category list --- serializer: categories.serializers.CategorySerializer responseMessages: - code: 401 message: Unauthorized. Authentication credentials were not provided. Invalid token. - code: 403 message: Forbidden. - code: 404 message: Not found """ if request.method == 'GET': employee = get_object_or_404(Employee, pk=employee_id) serializer = CategorySerializer(employee.categories, many=True) return Response(serializer.data, status=status.HTTP_200_OK)
class TopicSerializer(serializers.HyperlinkedModelSerializer): # owner = serializers.ReadOnlyField(source='owner.username') category = CategorySerializer(read_only=True) category_id = serializers.IntegerField(write_only=True) category_name = serializers.CharField(read_only=True) class Meta: model = Topic fields = ('topic_name', 'category', 'category_id', 'category_name') read_only_fields = ('category_id', ) # class UserSerializer(serializers.HyperlinkedModelSerializer): # snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail', read_only=True) # class Meta: # model = User # fields = ('url', 'username', 'snippets')
def update_category(request, category_id): payload = json.loads(request.body) try: category_item = Category.objects.filter(id=category_id) category_item.update(**payload) category = Category.objects.get(id=category_id) serializer = CategorySerializer(category) return JsonResponse(serializer.data, safe=False, status=status.HTTP_200_OK) except ObjectDoesNotExist as e: return JsonResponse({'error': str(e)}, safe=False, status=status.HTTP_404_NOT_FOUND) except Exception: return JsonResponse({'error': 'Something terrible went wrong'}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
class CampaingHeaderSerializer(serializers.ModelSerializer): """campaing header serializer""" category = CategorySerializer() class Meta: model = CampaingHeader fields = ( "id", "user", "category", "city", "qty_day", "amount", "amount_reached", "percent_reached", "qty_day_left", "role", "code_campaing", ) read_only_fields = ("id", )
def get(self, *args, **kwargs): products = Product.objects.all() categories = Category.objects.all() main_categories = MainCategory.objects.all() posts = Post.objects.all().[:3] products_ser = ProductDetailSerializer(products, many=True).data categories_ser = CategorySerializer(categories, many=True).data main_categories_ser = MainCategorySerializer(main_categories, many=True).data post_ser = PostSerializer(posts, many=True).data products_ser_json = json.dumps(products_ser) categories_ser_json = json.dumps(categories_ser) main_categories_ser_json =json.dumps(main_categories_ser) post_ser_json = json.dumps(post_ser) context = { 'products' : products_ser_json, 'categories' : categories_ser_json, 'main_categories' : main_categories_ser_json, 'posts' : post_ser_json, } return render(self.request, "views/index.html", context)
def get(self, *args, **kwargs): try: products_list = Product.objects.all() categories = Category.objects.all() main_categories = MainCategory.objects.all() posts = Post.objects.all()[:3] categories_ser = CategorySerializer(categories, many=True).data main_categories_ser = MainCategorySerializer(main_categories, many=True).data post_ser = PostSerializer(posts, many=True).data categories_ser_json = json.dumps(categories_ser) main_categories_ser_json =json.dumps(main_categories_ser) post_ser_json = json.dumps(post_ser) paginator = Paginator(products_list, 12) page = self.request.GET.get('page') try: products = paginator.page(page) except PageNotAnInteger: products = paginator.page(1) except EmptyPage: products = paginator.page(paginator.num_pages) products_ser = ProductDetailSerializer(products, many=True).data products_ser_json = json.dumps(products_ser) context = { 'products' : products_ser_json, 'categories' : categories_ser_json, 'main_categories' : main_categories_ser_json, 'posts' : post_ser_json, 'page' : page, } return render(self.request, "views/index.html", context) except ObjectDoesNotExist: message = messages.ERROR("سرور ترکیده") return HttpResponseBadRequest("Object Does Not Exist")
class DonationSerializer(serializers.ModelSerializer): category_id = serializers.PrimaryKeyRelatedField( source='category', required=True, queryset=Category.objects.all()) category = CategorySerializer(read_only=True) donor = UserSerializer(read_only=True) images = DonationImageSerializer(many=True, read_only=True) class Meta: model = Donation fields = ( 'id', 'description', 'long_description', 'category_id', 'category', 'donor', 'status', 'images', 'started_at', 'finalized_at', 'canceled_at', 'updated_at', ) read_only_fields = ( 'id', 'category', 'donor', 'status', 'images', 'started_at', 'finalized_at', 'canceled_at', 'updated_at', ) def create(self, validated_data): return super(DonationSerializer, self) \ .create({**validated_data, 'donor': self.context['request'].user})
def category_detail(request, pk, format=None): """Retrieve, update or delete a code category.""" try: category = Category.objects.get(pk=pk) except Category.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = CategorySerializer(category) return Response(serializer.data) elif request.method == 'PUT': serializer = CategorySerializer(category, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': category.delete() return Response(status=status.HTTP_204_NO_CONTENT)
def perform_create(self, serializer: CategorySerializer): serializer.save(user=self.request.user) return super(CategoryViewSet, self).perform_create(serializer)
def post(self, request): serializer = CategorySerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def get(self, request): categories = Category.objects.all() serializer = CategorySerializer(categories, many=True) return Response(serializer.data)
def get_category(self, obj): return CategorySerializer(obj.category.all(), many=True).data
def retrieve(self, request, pk=None, **kwargs): category = get_object_or_404(self.queryset, pk=pk) serializer = CategorySerializer(category) return Response(serializer.data, status=status.HTTP_200_OK)
def get_category(self, obj): return CategorySerializer(obj.category).data
def get(self, request, pk): category = get_object_or_404(Category, pk=pk) serializer = CategorySerializer(category) return Response(serializer.data, status=status.HTTP_200_OK)
def get_categories_of_product(self, request, pk=None): categories = Product.objects.get(pk=pk).get_all_categories() serializer = CategorySerializer(categories, many=True, context={'request': request}) return Response(data=serializer.data, status=status.HTTP_200_OK)