11from django .db import models
2+ from django .utils import timezone
3+ from django .conf import settings
24
35# Create your models here.
6+ class RankedProduct (models .Model ):
7+ product_id = models .CharField (max_length = 100 , unique = True , db_index = True ) # 제품 id
8+ name = models .CharField (max_length = 200 )
9+ brand = models .CharField (max_length = 100 )
10+ price = models .CharField (max_length = 100 , verbose_name = "가격" )
11+ image_url = models .CharField (max_length = 500 )
12+ like_count = models .PositiveIntegerField (default = 0 )
13+ created_at = models .DateTimeField (auto_now_add = True )
14+
15+ def __str__ (self ):
16+ return f"[{ self .brand } ] { self .name } "
17+
18+ class VotingSession (models .Model ):
19+ """
20+ 하나의 투표 세션 - 24시간 간격으로 생성
21+ """
22+ #session_id =
23+ product1 = models .ForeignKey (RankedProduct , on_delete = models .CASCADE , related_name = 'product1_sessions' )
24+ product2 = models .ForeignKey (RankedProduct , on_delete = models .CASCADE , related_name = 'product2_sessions' )
25+ product1_votes = models .PositiveIntegerField (default = 0 )
26+ product2_votes = models .PositiveIntegerField (default = 0 )
27+ is_active = models .BooleanField (default = True )
28+
29+ winner = models .ForeignKey (RankedProduct , on_delete = models .SET_NULL , null = True , blank = True , related_name = 'won_sessions' )
30+
31+ start_time = models .DateTimeField (auto_now_add = True )
32+ end_time = models .DateTimeField (null = True , blank = True )
33+
34+ def __str__ (self ):
35+ status = "Active" if self .is_active else "Finished"
36+ return f"Session { self .id } : { self .product1 .name } vs { self .product2 .name } ({ status } )"
37+
38+ # session is_active false 변경 함수
39+ def close_session (self ):
40+ self .end_time = timezone .now ()
41+ self .is_active = False
42+
43+ if self .product1_votes > self .product2_votes :
44+ self .winner = self .product1
45+ elif self .product2_votes > self .product1_votes :
46+ self .winner = self .product2
47+
48+ self .save ()
49+
50+ # 세션 - 투표 - 사용자를 잇는 투표 모델
51+ class Vote (models .Model ):
52+ session = models .ForeignKey (VotingSession , on_delete = models .CASCADE )
53+ user = models .ForeignKey (settings .AUTH_USER_MODEL , on_delete = models .CASCADE )
54+ voted_product = models .ForeignKey (RankedProduct , on_delete = models .CASCADE )
55+ created_at = models .DateTimeField (auto_now_add = True )
56+
57+ class Meta :
58+ # 한 사용자는 한 세션에 하나의 투표만 가능
59+ unique_together = ('session' , 'user' )
0 commit comments