async def to_json(self, result): json = await super(MaterialCategorySerializer, self).to_json(result) async with self.context['request'].app['db'].acquire() as conn: query = Category.select().where(Category.c.id == json['category']) result = await conn.execute(query) serializer = CategorySerializer() category = await serializer.to_json(result) json = category return json
async def search_categories(request): async with request.app['db'].acquire() as conn: text = request.query.get('text') if text is None: raise ValidationError(dict(text='This query parameters is required')) query = Category.select().where(Category.c.name.like('%{}%'.format(text))) result = await conn.execute(query) serializer = CategorySerializer(many=True) data = await serializer.to_json(result) return web.json_response(data)
class MovieDetailSerializer(serializers.ModelSerializer): """Полный фильм""" category = CategorySerializer(read_only=True) directors = ActorListSerializer(read_only=True, many=True) actors = ActorListSerializer(read_only=True, many=True) genres = serializers.SlugRelatedField(slug_field="name", read_only=True, many=True) reviews = ReviewSerializer(many=True) class Meta: model = Movie exclude = ("draft", )
class RestaurantSerializer(serializers.ModelSerializer): category = CategorySerializer(read_only=True) total_of_reviews = serializers.SerializerMethodField() avg_rating = serializers.SerializerMethodField() def get_total_of_reviews(self, restaurant): return Review.objects.filter(idRestaurant=restaurant).count() def get_avg_rating(self, restaurant): return Restaurant.objects.filter(id=restaurant.id).aggregate(rating=Avg('fk_Review_to_Restaurant__rating')) class Meta: model = Restaurant fields = "__all__"
class DealSerializer(serializers.HyperlinkedModelSerializer): current_stats = DealStatsSerializer(read_only=True) city = CitySerializer(read_only=True) category = CategorySerializer(read_only=True) ends_on = serializers.SerializerMethodField('format_end_date') created_on = serializers.SerializerMethodField('format_start_date') class Meta: model = Deal fields = ('url', 'title', 'sell_price', 'initial_price', 'discount', 'saving', 'city', 'category', 'current_stats', 'created_on', 'ends_on') def format_start_date(self, obj): return obj.created_on.strftime('%Y-%m-%d-%H-%M-%S') def format_end_date(self, obj): return obj.ends_on.strftime('%Y-%m-%d-%H-%M-%S')
class BookSerializer(serializers.ModelSerializer): categories = CategorySerializer(many=True) class Meta: model = Book fields = ( 'id', 'title', 'author', 'price', 'discount', 'description', 'rate', 'year', 'editorial', 'image', 'book_cover', 'categories', 'in_home', )
def get_categories(self, obj): return CategorySerializer(obj.category_set.all(), many=True).data