(참고 : https://velog.io/@valentin123/TIL-self-referencing-model )
제품 상세 페이지로 가보면, 하단에 추천 상품들이 떠 있는 경우가 많다.
이 경우, 장고에서 모델링을 어떻게 해주어야 할까.
상품(Product) 테이블에서 자기 테이블과 many to many 관계를 설정해주면 된다. 하나의 상품은 여러 개의 추천 상품을 가질 수 있고, 하나의 추천된 상품은 여러 개의 제품에 추천될 수 있기 때문이다.
class Product(models.Model):
sub_category = models.ForeignKey('ProductSubCategory', on_delete=models.CASCADE)
name = models.CharField(max_length=50, null=True)
description = models.CharField(max_length=500, null=True)
filter_list = models.ManyToManyField('FilterList', through='ProductFilter', related_name=('products'))
color = models.ManyToManyField('Color', through='ProductImage', related_name=('products'))
recommend_product = models.ManyToManyField('self', through='RecommendProduct', symmetrical=False)
class Meta:
db_table='products'
class RecommendProduct(models.Model):
product = models.ForeignKey('Product', on_delete=models.CASCADE, related_name='recommend_products')
recommend_product = models.ForeignKey('Product', on_delete=models.CASCADE, related_name='products')
class Meta:
db_table='recommend_products'
Product 클래스에서 recommend_product 라는 필드를 'self' 즉, 자기 자신을 참조하는 다대다 관계를 설정해준다. 그리고 중간 테이블로 'RecommendProduct'가 들어가게 된다. 즉 자기 자신의 테이블과 다대다 관계를 설정해주는 것이다.
RecommendProduct 테이블의 경우, 필드는 전부 Product 테이블을 바라본다. Foreign Key 로!!
symmetrical 은 A라는 상품에서 B 상품이 추천될 수 있지만, B라는 상품에서는 A가 추천되지 않을 수 있기 때문에 False로 설정해준다.
'Django' 카테고리의 다른 글
[Django] Many to Many 다대다 관계 (0) | 2020.07.05 |
---|---|
[Django] CSV데이터_데이터베이스_업로드 (1) | 2020.06.28 |
[Django]Select_related (0) | 2020.06.25 |