Skip to content

Commit b025707

Browse files
authored
Merge pull request #213 from pirogramming/develop
[Feat] db 꼬인 문제 해결하고 제조사 추출하는 코드 작성
2 parents 3af52c7 + 4b1e88a commit b025707

25 files changed

Lines changed: 114 additions & 200 deletions

diets/views.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def food_to_dict(food):
5454
"trans_fatty_acids": safe_float(getattr(food, "trans_fatty_acids", 0)),
5555
"serving_size": safe_float(getattr(food, "serving_size", 0)),
5656
"weight": safe_float(getattr(food, "weight", 0)),
57-
"company_name": safe_str(getattr(food, "mallName", "") or getattr(food, "company_name", "") or ""),
57+
"company_name": safe_str(getattr(food, "company_name", "") or ""),
5858
"score": safe_float(getattr(food, "nutrition_score", 0)),
5959
"letter_grade": safe_str(getattr(food, "nutri_score_grade", "") or letterGrade(food) or ""),
6060
"nutri_score_grade": safe_str(getattr(food, "nutri_score_grade", "") or letterGrade(food) or "")
@@ -181,7 +181,7 @@ def diet_list(request):
181181
recent_foods.append({
182182
"food_id": str(cur_food.food_id),
183183
"food_name" : cur_food.food_name,
184-
"company_name": cur_food.mallName or cur_food.company_name,
184+
"company_name": cur_food.company_name,
185185
"food_img": cur_food.image_url or cur_food.food_img
186186
})
187187
cnt += 1 #식품 카운팅
@@ -212,7 +212,7 @@ def diet_search(request):
212212
food_data = dict() #food의 정보를 담을 dict
213213
food_data['food_id'] = str(food.food_id)
214214
food_data['food_name'] = food.food_name
215-
food_data['company_name'] = food.mallName or food.company_name
215+
food_data['company_name'] = food.company_name
216216
food_data['food_img'] = food.image_url or food.food_img
217217
ret['foods'].append(food_data) #food_data 에 정보를 모두 담았으니 ret['foods']에 추가
218218

foods/admin.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44

55
@admin.register(Food)
66
class FoodAdmin(admin.ModelAdmin):
7-
list_display = ['food_id', 'food_name', 'company_name', 'food_category', 'mallName', 'lprice']
8-
list_filter = ['food_category', 'company_name', 'mallName']
7+
list_display = ['food_id', 'food_name', 'company_name', 'food_category', 'lprice']
8+
list_filter = ['food_category', 'company_name']
99
search_fields = ['food_name', 'company_name', 'representative_food']
1010
readonly_fields = ['food_id']
1111

@@ -29,7 +29,7 @@ class FoodAdmin(admin.ModelAdmin):
2929
'classes': ('collapse',)
3030
}),
3131
('가격 정보', {
32-
'fields': ('mallName', 'lprice', 'discount_price', 'shop_url', 'image_url'),
32+
'fields': ('lprice', 'discount_price', 'shop_url', 'image_url'),
3333
'classes': ('collapse',)
3434
}),
3535
('기타 정보', {
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# Generated by Django 5.2.4 on 2025-08-18 10:38
2+
3+
from django.db import migrations
4+
5+
6+
class Migration(migrations.Migration):
7+
8+
dependencies = [
9+
('foods', '0010_remove_food_shop_name'),
10+
]
11+
12+
operations = [
13+
migrations.RemoveField(
14+
model_name='food',
15+
name='mallName',
16+
),
17+
]

foods/models.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,6 @@ class Food(models.Model):
5353
# 가격 정보 (CSV 칼럼에 맞춰 추가)
5454
lprice = models.BigIntegerField(null=True, blank=True) # 네이버 쇼핑 최저가
5555
discount_price = models.BigIntegerField(null=True, blank=True)
56-
mallName = models.CharField(max_length=100, null=True, blank=True) # 쇼핑몰 이름
5756
shop_url = models.URLField(null=True, blank=True)
5857
image_url = models.URLField(null=True, blank=True)
5958

mypage/views.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ def favorite_food_list(request):
114114
"food_id": str(food.food_id),
115115
"food_name": food.food_name,
116116
"food_img": getattr(food, 'image_url', '') or getattr(food, 'food_img', '') or "http://example.com/default_food.png",
117-
"company_name": getattr(food, 'mallName', '') or getattr(food, 'company_name', '') or "Unknown",
117+
"company_name": getattr(food, 'company_name', '') or "Unknown",
118118
"calorie": int(food.calorie) if getattr(food, 'calorie', None) else 0,
119119
"created_at": getattr(f, 'created_at', None),
120120
})

products/views.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,11 +73,10 @@ def _product_dict(food, is_favorite: bool):
7373
"trans_fatty_acids": safe_float(food.trans_fatty_acids),
7474
"nutritional_value_standard_amount": safe_int(food.nutritional_value_standard_amount),
7575
"weight": safe_float(food.weight),
76-
"company_name": safe_str(food.mallName) or safe_str(food.company_name),
76+
"company_name": safe_str(food.company_name),
7777
"nutrition_score": safe_float(food.nutrition_score),
7878
"nutri_score_grade": safe_str(food.nutri_score_grade),
7979
"lprice": safe_int(food.lprice),
80-
"shop_name": safe_str(food.mallName),
8180
"shop_url": safe_str(food.shop_url),
8281
"sugar_level": None,
8382
"saturated_fatty_acids_level": None,
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
#!/usr/bin/env python3
2+
"""
3+
20250327_가공식품DB_147999건.xlsx에서 제조사 정보를 추출하여
4+
food_clean_data.csv의 company_name을 업데이트하는 스크립트
5+
"""
6+
7+
import pandas as pd
8+
9+
def main():
10+
print("제조사 정보 추출 및 매핑 시작...")
11+
12+
try:
13+
# 1. 원본 Excel 파일 읽기
14+
print("20250327_가공식품DB_147999건.xlsx 로딩 중...")
15+
df_original = pd.read_excel('/Users/kimminji/Desktop/Healthtant/20250327_가공식품DB_147999건.xlsx')
16+
print(f"원본 데이터: {len(df_original)}개 행")
17+
18+
# 2. food_clean_data.csv 읽기
19+
print("food_clean_data.csv 로딩 중...")
20+
df_food = pd.read_csv('/Users/kimminji/Desktop/Healthtant/food_clean_data.csv')
21+
print(f"현재 식품 데이터: {len(df_food)}개 행")
22+
23+
# 3. 제조사 정보 추출 (식품코드 -> 제조사명)
24+
manufacturer_mapping = {}
25+
for idx, row in df_original.iterrows():
26+
food_code = str(row['식품코드']).strip()
27+
manufacturer = str(row['제조사명']).strip() if pd.notna(row['제조사명']) else ''
28+
29+
# 제조사명이 없으면 수입업체명이나 유통업체명 사용
30+
if not manufacturer or manufacturer == 'nan':
31+
manufacturer = str(row['수입업체명']).strip() if pd.notna(row['수입업체명']) else ''
32+
if not manufacturer or manufacturer == 'nan':
33+
manufacturer = str(row['유통업체명']).strip() if pd.notna(row['유통업체명']) else ''
34+
35+
if manufacturer and manufacturer != 'nan':
36+
manufacturer_mapping[food_code] = manufacturer
37+
38+
print(f"제조사 정보를 찾은 식품: {len(manufacturer_mapping)}개")
39+
40+
# 4. food_clean_data.csv의 company_name 업데이트
41+
updated_count = 0
42+
for idx, row in df_food.iterrows():
43+
food_id = str(row['food_id']).strip()
44+
if food_id in manufacturer_mapping:
45+
df_food.at[idx, 'company_name'] = manufacturer_mapping[food_id]
46+
updated_count += 1
47+
48+
print(f"업데이트된 식품: {updated_count}개")
49+
50+
# 5. 업데이트된 CSV 저장
51+
output_file = '/Users/kimminji/Desktop/Healthtant/food_clean_data_updated.csv'
52+
df_food.to_csv(output_file, index=False, encoding='utf-8')
53+
print(f"업데이트된 파일 저장: {output_file}")
54+
55+
# 6. 통계 출력
56+
total_foods = len(df_food)
57+
foods_with_manufacturer = len(df_food[df_food['company_name'].notna() & (df_food['company_name'] != '') & (df_food['company_name'] != 'UNKNOWN')])
58+
print(f"\n=== 통계 ===")
59+
print(f"전체 식품: {total_foods}개")
60+
print(f"제조사 정보 있음: {foods_with_manufacturer}개 ({foods_with_manufacturer/total_foods*100:.1f}%)")
61+
62+
# 7. 샘플 데이터 확인
63+
print(f"\n=== 업데이트된 샘플 데이터 ===")
64+
sample = df_food[df_food['company_name'].notna() & (df_food['company_name'] != '') & (df_food['company_name'] != 'UNKNOWN')].head(10)
65+
for _, row in sample.iterrows():
66+
print(f"ID: {row['food_id']}, 식품명: {row['food_name']}, 제조사: {row['company_name']}")
67+
68+
except Exception as e:
69+
print(f"오류 발생: {e}")
70+
import traceback
71+
traceback.print_exc()
72+
73+
if __name__ == "__main__":
74+
main()

scripts/extract_manufacturers.py

Lines changed: 0 additions & 69 deletions
This file was deleted.

scripts/health_check.py

Lines changed: 0 additions & 43 deletions
This file was deleted.

scripts/insert_food_postgresql.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,6 @@ def main():
148148
# 2) 매핑 - food_clean_data.csv 칼럼에 맞춰 수정
149149
csv_to_db = {
150150
'food_id': 'food_id',
151-
'shop_name': 'mallName',
152151
'price': 'lprice',
153152
'discount_price': 'discount_price',
154153
'shop_url': 'shop_url',

0 commit comments

Comments
 (0)