07/17 Django, DB..

Mun Lee·2020년 7월 17일
0

지난주 금요일부터 지금까지 스타벅스에 있는 값을 크롤링해와서 csv로 옮긴 다음에 MYSQL을 통하여 DB에 값을 넣는거 이해하는데 오랜시간이 걸렸다.
지금도 확실히 이해를 하지는 못했지만 하나하나씩 해보면서 익숙해져가는수밖에 없다고 생각한다.

-CSV에 있는 값을 DB에 넣어주기
:menu, category, drink, image, description, size, nutrition_information,allergy까지 만들었고, allergy_drink ManyToMany 이거 하나 남았다.

 from starbucks_app.models import *
#a = Menu.objects.get(name='음료').id
ALLERGY_CSV_PATH = './starbucks_product.csv'
with open(ALLERGY_CSV_PATH, newline='') as allergy_csvfile:
    data_reader = csv.reader(allergy_csvfile)
    next(data_reader,None)
    
    
    result =[]
    for row in data_reader:
        for abc in row[15].split("'"):
            if(abc !=  '[' and abc != ']' and abc != ', '):
                #print(abc.replace(' ',''))

                abcabc = abc.replace(' ','')
                result = set(result)
                result.add(abcabc)
                
for i in result:
    Allergy.objects.create(
    
        name = i
    )    

이건 csv에 있는 알레르기 값들을 db에 넣어주기 위한 코드이다.
ALLERGY_CSV_PATH = './starbucks_product.csv'
with open(ALLERGY_CSV_PATH, newline='') as allergy_csvfile:
data_reader = csv.reader(allergy_csvfile)
next(data_reader,None)

data_reader =csv.reader(allerty_csvfile)은 csv에 있는 값들을 data_reader에 넣어준다는 의미

result =[]
for row in data_reader:
for abc in row[15].split("'"):
if(abc != '[' and abc != ']' and abc != ', '):
#print(abc.replace(' ',''))

            abcabc = abc.replace(' ','')
            result = set(result)
            result.add(abcabc)

row[15] 이 값은 [' 대두 ', ' 우유'] 이게 List같아보이는데 type을 통해 확인해보면 str인것을 확인할 수 있다. DB에는

이렇게 중복되지 않게 뽑고 값만 뽑아주기 위해서
row[15].split("'")을 하여 '을 기준으로 분리를 시켜주면
[
대두
,
]
이렇게 나온다. 그래서 저 대두값만 뽑아주기 위해서
for abc in row[15].split("'"):
if(abc != '[' and abc != ']' and abc != ', '):

가른다음에 if문을 활용하여 저 3개가 아니라면
abcabc = abc.replace(' ','')
result = set(result)
result.add(abcabc)

for i in result:
Allergy.objects.create(

    name = i
)               
            

' ' 을 ''로 바꿔주고 데이터의 중복을 없애주기 위해서 set으로 형태를 바꿔준다.

            
profile
개발자가 되고자 하는 30살

0개의 댓글