2022.04.01 til

이산·2022년 4월 2일
0

TIL

목록 보기
13/22

djanto extensions에서 db 데이터를 불러오는 법을 배우고 그동안 고생하던 csv 파일을 db에 한번에 넣을 수 있도록 코드를 작성했다. 친구 개발자의 도움을 많이 받고 많이 배우는 시간이었다.

import json
from django.db import connection
from products.models import *
import csv


def run():
    Category.objects.all().delete()
    Product.objects.all().delete()
    Ingredient.objects.all().delete()
    ProductSkintype.objects.all().delete()
    ProductImage.objects.all().delete()
    ProductIngredient.objects.all().delete()
    SkinType.objects.all().delete()
    
    with connection.cursor() as cursor:
        cursor.execute('ALTER TABLE categories AUTO_INCREMENT = 1')
        cursor.execute('ALTER TABLE products AUTO_INCREMENT = 1')
        cursor.execute('ALTER TABLE ingredients AUTO_INCREMENT = 1')
        cursor.execute('ALTER TABLE product_imgaes AUTO_INCREMENT = 1')
        cursor.execute('ALTER TABLE product_ingredients AUTO_INCREMENT = 1')
        cursor.execute('ALTER TABLE product_skintypes AUTO_INCREMENT = 1')
        cursor.execute('ALTER TABLE skin_types AUTO_INCREMENT = 1')

    with open('categories.csv') as in_file:

        data_reader = csv.reader(in_file, delimiter = ':')
        next(data_reader, None)

        for row in data_reader:
            if row[0]:
                category_name    = row[1]
                main_description = row[2]
                sub_description  = row[3]

                Category.objects.create(
                    category_name    = category_name,
                    main_description = main_description,
                    sub_description  = sub_description
                )
                
    with open('products.csv') as in_file:

        data_reader = csv.reader(in_file, delimiter = ',')
        next(data_reader, None)

        for row in data_reader:
            if row[0]:
                name        = row[3]
                price       = row[4]
                size        = row[5]
                description = row[6]
                feeling     = row[7]
                howtouse    = json.loads(row[8])
                category_id = row[9]
                badge       = row[10]
                
                Product.objects.create(
                    name        = name,
                    price       = price,
                    size        = size,
                    description = description,
                    feeling     = feeling,  
                    howtouse    = howtouse,
                    category_id = category_id,
                    badge       = badge
                )

    with open('skintypes.csv') as in_file:

        data_reader = csv.reader(in_file, delimiter = ':')
        next(data_reader, None)

        for row in data_reader:
            if row[0]:
                skin_type = row[1]

                skin_type_instance = SkinType.objects.create(
                    skin_type = skin_type
                )
                print(skin_type_instance)

    new_list = ['skintypes.csv','products.csv']
    for i in new_list:

        with open('product_skintypes.csv') as in_file:

            data_reader = csv.reader(in_file, delimiter = ':')
            next(data_reader, None)

            for row in data_reader:
                if row[0]:
                    product_id = row[1]
                    skint_type_id = row[2]

                    ProductSkintype.objects.create(
                        product_id=product_id,
                        skin_type_id=skint_type_id
                    )


    with open('ingredients.csv') as in_file:
        data_reader = csv.reader(in_file, delimiter = ':')
        next(data_reader, None)

        for row in data_reader:
            if row[0]:
                ingredients = row[1]

                Ingredient.objects.create(
                    ingredients=ingredients
                )

    with open('product_ingredients.csv') as in_file:
        
        data_reader = csv.reader(in_file, delimiter = ':')
        next(data_reader, None)

        for row in data_reader:
            if row[0]:
                squence = row[0]
                ingredient_id = row[1]
                product_id = row[2]

                ProductIngredient.objects.create(
                    squence=squence,
                    ingredient_id=ingredient_id,
                    product_id=product_id
                )

    with open('product_images.csv') as in_file:
        data_reader = csv.reader(in_file, delimiter = ',')
        next(data_reader, None)

        for row in data_reader:
            if row[0]:
                image_url = row[2]
                product_id = row[1]

                ProductImage.objects.create(
                    image_url=image_url,
                    product_id=product_id,
                )

후에는 장바구니 담기 기능을 구현해보았다.생각보다 쉬워서 그동안 공부한 보람이 느껴졌다. 만드는 홈페이지의 카트는 수량이 5개 까지만 가능하기 때문에 조건문을 사용했고 카트에 넣기 위에 제품 상세페이지에서 누를 때 db에 테이블이 생성될 수 있도록 했다.

class CartView(View):
    @logindeco
    def post(self, request):
        try:
            data       = json.loads(request.body)
            user       = request.user
            product_id = data['product_id']
            
            if Cart.objects.filter(product_id = product_id).exists():
                cart = Cart.objects.get(product_id = product_id)
                if cart.quantity <= 0 or cart.quantity >= 5:
                    return JsonResponse({'message' : 'INVALID_QUANTITY'}, status = 400)
                cart.quantity += 1
                cart.save()
                return JsonResponse({'message' : 'QUANTITY_CHANGED'}, status = 200)

            Cart.objects.create(
                user       = user,
                product_id = product_id,
                quantity   = 1
            )
            return JsonResponse({'message' : 'CART_CREATED'}, status = 201)

        except KeyError:
            return JsonResponse({'message' : 'KEY_ERROR'}, status = 400)
        except Product.DoesNotExist:
            return JsonResponse({'message' : 'PRODUCT_DOES_NOT_EXIT'}, status = 400)
profile
백엔드 개발자입니다.

0개의 댓글