바뀜

둘러보기로 가기 검색하러 가기
1,640 바이트 추가됨 ,  2024년 4월 2일 (화) 13:32
편집 요약 없음
1번째 줄: 1번째 줄:  
[[분류:장고 모델]]
 
[[분류:장고 모델]]
   −
==외부 모델과 연결==
+
=tip.=
외부모델을 연결한다든가 다양한 상황이 생길 수 있다. 이때 외부모델을 임포트해와야 하는데, 다음과 같은 형식으로 불러온다.
     −
from 앱이름.models import 모델명
+
= 메타클래스 =
   −
위 형식으로 임포트 해서 사용할 수 있다.
+
모델에 메타데이터를 제공하기 위해 사용된다.<syntaxhighlight lang="python">
{| class="wikitable"
+
class 모델명(models.Model):
!
+
    ...
!
+
   
!
+
    class Meta:
|-
+
       
|댓글달기
+
</syntaxhighlight>
|댓글을 다는 기능을 구현하기 위해 댓글 테이블을 만들려면 기존 글에 대한 ForeignKey를 사용해야 한다.
+
 
on_delete-models.CASCADE 옵션은 기존 글이 사라질때 같이 사라지게 한다는 의미이다.
+
=== unique_together ===
|<syntaxhighlight lang="python">
+
해당 속성의 조합이 단 1개만 허용될 때 사용한다.  DB에서의 조건을 제약한다.
class 댓글(models.Model):
+
 
     기존글 = models.ForeignKey(기존모델, on_delete-models.CASCADE)
+
좋아요, 북마크 등을 만들 때 사용한다.
 +
 
 +
(훗날 UniqueConstraint로 바뀌게 될듯)<syntaxhighlight lang="python">
 +
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')
 +
            )
 +
</syntaxhighlight>[공식 메뉴얼에선 unique_together 안에 튜플이 아니라, 리스트로 하는데.. 둘다 가능한지 확인이 필요해보인다.
 +
 
 +
=== ordering ===
 +
모델 자체를 어떤 방식으로 정렬할지 지정한다.<syntaxhighlight lang="python">
 +
class 모델명
 +
    ...
 +
    created_at = models.DateTimeField(auto_now_add=True)
 +
    ...
 +
   
 +
    class Meta:
 +
        ordering = ['-created_at']  #created_at 속성의 역순으로 정렬한다는 의미.
 +
</syntaxhighlight>
 +
 
 +
= 모델 안에서 정의하는 함수 =
 +
모델 클래스 안에 함수를 정의할 수 있다. 객체.함수() 형태로 뷰에서 사용할 수 있고, <nowiki>{{객체.함수}}</nowiki> 형태로 탬플릿에서 사용할 수도 있다..! 이런 기능이 있다면 엄청나게 많은, 간단한 활용이 가능해지지. url.py를 거치지 않고도 하위객체를 생성한다든가.
 +
 
 +
= 기존 함수 오버라이딩 =
 +
save, delete 등 함수를 오버라이딩하여 특수한 처리를 할 수 있다.<syntaxhighlight lang="python">
 +
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)
 
</syntaxhighlight>
 
</syntaxhighlight>
|}
  −
==tip.==
 

둘러보기 메뉴