3. 장고 모델 활용

Pywiki
둘러보기로 가기 검색하러 가기


1 tip.[편집 | 원본 편집]

2 메타클래스[편집 | 원본 편집]

모델에 메타데이터를 제공하기 위해 사용된다.

class 모델명(models.Model):
    ...
    
    class Meta:

2.1 unique_together[편집 | 원본 편집]

해당 속성의 조합이 단 1개만 허용될 때 사용한다. DB에서의 조건을 제약한다.

좋아요, 북마크 등을 만들 때 사용한다.

(훗날 UniqueConstraint로 바뀌게 될듯)

class Like(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    writing = models.ForeignKey(모델명, on_delete=models.CASCADE)
    
    class Meta:
        unique_together = (
            ('user','post')
            )

[공식 메뉴얼에선 unique_together 안에 튜플이 아니라, 리스트로 하는데.. 둘다 가능한지 확인이 필요해보인다.

2.2 ordering[편집 | 원본 편집]

모델 자체를 어떤 방식으로 정렬할지 지정한다.

class 모델명
    ...
    created_at = models.DateTimeField(auto_now_add=True)
    ...
    
    class Meta:
        ordering = ['-created_at']  #created_at 속성의 역순으로 정렬한다는 의미.

3 모델 안에서 정의하는 함수[편집 | 원본 편집]

모델 클래스 안에 함수를 정의할 수 있다. 객체.함수() 형태로 뷰에서 사용할 수 있고, {{객체.함수}} 형태로 탬플릿에서 사용할 수도 있다..! 이런 기능이 있다면 엄청나게 많은, 간단한 활용이 가능해지지. url.py를 거치지 않고도 하위객체를 생성한다든가.

4 기존 함수 오버라이딩[편집 | 원본 편집]

save, delete 등 함수를 오버라이딩하여 특수한 처리를 할 수 있다.

class 모델명
    ...
    created_at = models.DateTimeField(auto_now_add=True)
    ...
    
    def save(self, *args, **kwargs):
        if self.pk is None:
            # 새로운 객체 생성 시 실행할 로직
            if not self.name and self.grade and self.cl_num:
                self.name =  f'{self.grade}학년 {self.cl_num}반'
        else:
            # 객체 업데이트 시 실행할 로직
            pass
        super().save(*args, **kwargs)  # 원래의 save 메서드 호출
        homework_box, created = HomeworkBox.objects.get_or_create(homeroom=self)