Exemple #1
0
 def post(self):
     try:
         category = CategorySchema().load(request.get_json())
     except ValidationError as err:
         return str(err)
     return CategorySchema().dump(
         Category.objects.create(**category).save())
Exemple #2
0
    def put(self, cat_id=None):
        if not cat_id:
            return "Відсутній id в url"
        json_data = json.dumps(request.json)
        try:
            try:
                category_data = CategorySchema().loads(json_data)
                category_data = json.loads(
                    CategorySchema().dumps(category_data))

                category = Category(id=cat_id)
                parent_category = Category.objects.filter(
                    id=category_data['parent_category'])

                # Наступний if не дозволяє створювати підкатегорії другого рівня
                if not parent_category[0].parent_category:
                    category.update(id=cat_id,
                                    parent_category=parent_category[0].id,
                                    description=category_data['description'],
                                    name=category_data['name'])
                else:
                    category_data = "Заборонено створювати підкатегорії другого рівня"
            except ValidationError as error:
                category_data = error.messages
            return category_data
        except Val_error as error:
            data = "Введений ID у невірному форматі або неіснуючий: " + str(
                error)
            return data
Exemple #3
0
 def get(self, c_id=None):
     if c_id:
         category = Category.objects.get(id=c_id)
         category = CategorySchema().dump(category)
         return category
     else:
         categories = Category.objects
         return CategorySchema().dump(categories, many=True)
Exemple #4
0
def add_categories():
    for category in CATEGORIES:
        if not category.get("parent_category"):
            if not Category.objects.filter(**category):
                category = CategorySchema().load(category)
                print(
                    f"Category = {Category.objects.create(**category).save()}")
Exemple #5
0
    def delete(self, cat_id=None):
        if not cat_id:
            return "Відсутній id в url"
        try:
            category_to_delete = Category.objects.get(id=cat_id)
            category_to_delete = CategorySchema().dump(category_to_delete)

            reference_list_child_cat = Category.objects.filter(
                parent_category=category_to_delete['id'])
            # При видаленні категорії в разі наявності в них підкатегорій наступний блок if/for видаляє всі їх також
            if reference_list_child_cat:
                for category in reference_list_child_cat:
                    # Продукти, що належать до підкатегорії видаляються в наступному циклі for
                    products_to_delete_list = Products.objects.filter(
                        category=category.id)
                    for product in products_to_delete_list:
                        product.delete()
                    category.delete()

            category = Category(id=cat_id)
            # Продукти, що належать до підкатегорії видаляються також разом із нею
            products_to_delete_list = Products.objects.filter(
                category=category.id)
            for product in products_to_delete_list:
                product.delete()
            category.delete()
            return category_to_delete
        except DoesNotExist as error:
            data = "За введеним ID наразі немає записів: " + str(error)
            return data
        except Val_error as error:
            data = "Введений ID у невірному форматі: " + str(error)
            return data
Exemple #6
0
    def post(self, *args):
        try:
            json_data = json.dumps(request.json)
            result = CategorySchema().loads(json_data)
            res = json.loads(CategorySchema().dumps(result))

            category = Category.objects.filter(id=result['parent_category'])

            # Наступний if не дозволяє створювати підкатегорії другого рівня
            if not category[0].parent_category:
                Category.objects.create(**res).save().to_json()
            else:
                res = "Заборонено створювати підкатегорії другого рівня"
        except ValidationError as error:
            return error.messages
        return res
Exemple #7
0
def add_subcategories():
    for category in CATEGORIES:
        if category.get("parent_category"):
            parent_category = Category.objects.filter(
                name=category['parent_category'])
            category['parent_category'] = str(parent_category[0].id)
            category = CategorySchema().load(category)
            print(
                f"Subcategory = {Category.objects.create(**category).save()}")
Exemple #8
0
 def get(self, cat_id=None):
     if cat_id:
         try:
             category = Category.objects.get(id=cat_id)
             category = CategorySchema().dump(category)
             return category
         except DoesNotExist as error:
             data = "За введеним ID наразі немає записів (або отриманий запис має посилання на " \
                "інший неіснуючий): " + str(error)
             return jsonify(data)
         except Val_error as error:
             data = "Введений ID у невірному форматі: " + str(error)
             return jsonify(data)
     else:
         try:
             categories = Category.objects
             return CategorySchema().dump(categories, many=True)
         except DoesNotExist as error:
             data = "Один з отриманих записів має посилання на інший неіснуючий: " + str(
                 error)
             return data
Exemple #9
0
def add_categories(add_root_categories_not_sub=True):
    if add_root_categories_not_sub:
        for category in CATEGORIES:
            if category.get("parent_category", None) is None:
                db_category = Category.objects.filter(**category)
                if db_category:
                    continue
                category = CategorySchema().load(category)
                print(f"Added: {Category.objects.create(**category).save()}")
    else:
        for category in CATEGORIES:
            if category.get("parent_category", None) is not None:
                parent_category = Category.objects.filter(name=category['parent_category'])
                if not parent_category:
                    print(f"Error adding {category}")
                    continue
                db_category = Category.objects.filter(name=category['name'],
                                                      parent_category=parent_category[0].id)
                if db_category:
                    print(f"Category {category} already exists")
                    continue
                category['parent_category'] = str(parent_category[0].id)
                category = CategorySchema().load(category)
                print(f"Added: {Category.objects.create(**category).save()}")