UniqueConstraint

khh180cm·2021년 2월 17일
0

order 별 status의 중복 생성을 방지하고 싶을 때


class Shipping(BaseModel):

    COMPANY_CHOICES = [
        ("CJ", "CJ대한통운"),
        ("PO", "우체국택배")
    ]
    order = models.ForeignKey("Order", on_delete=models.SET_NULL, null=True)
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True
    )
    status = models.CharField(max_length=20, verbose_name="배송 상태", default="출고 완료")
    detail = models.CharField(max_length=120, verbose_name="상세 설명", blank=True)
    invoice_number = models.CharField(max_length=20, verbose_name="운송장번호", blank=False, default=None)
    delivery_company = models.CharField(max_length=2, verbose_name="택배사", choices=COMPANY_CHOICES, default="CJ")
    place = models.CharField(max_length=25, blank=True, verbose_name="장소", default="쿠돈")

    def __str__(self):
        return self.status

    class Meta:
        db_table = "shippings"
        # 하나의 order는 unique한 status 저장
        constraints = [
            models.UniqueConstraint(fields=['order_id', 'status'], name="unique_status")
        ]

출처: https://stackoverflow.com/questions/2881043/django-create-a-unique-database-constraint-for-2-or-more-fields-together

0개의 댓글