"3. 장고 모델 활용"의 두 판 사이의 차이
둘러보기로 가기
검색하러 가기
(→메타클래스) |
|||
27번째 줄: | 27번째 줄: | ||
) | ) | ||
</syntaxhighlight>[공식 메뉴얼에선 unique_together 안에 튜플이 아니라, 리스트로 하는데.. 둘다 가능한지 확인이 필요해보인다. | </syntaxhighlight>[공식 메뉴얼에선 unique_together 안에 튜플이 아니라, 리스트로 하는데.. 둘다 가능한지 확인이 필요해보인다. | ||
+ | |||
+ | === ordering === | ||
+ | 모델 자체를 어떤 방식으로 정렬할지 지정한다.<syntaxhighlight lang="python"> | ||
+ | class 모델명 | ||
+ | ... | ||
+ | created_at = models.DateTimeField(auto_now_add=True) | ||
+ | ... | ||
+ | |||
+ | class Meta: | ||
+ | ordering = ['-created_at'] #created_at 속성의 역순으로 정렬한다는 의미. | ||
+ | </syntaxhighlight> |
2021년 6월 24일 (목) 23:49 판
1 tip.
1.1 메타클래스
모델에 메타데이터를 제공하기 위해 사용된다.
class 모델명(models.Model):
...
class Meta:
1.1.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 안에 튜플이 아니라, 리스트로 하는데.. 둘다 가능한지 확인이 필요해보인다.
1.1.2 ordering
모델 자체를 어떤 방식으로 정렬할지 지정한다.
class 모델명
...
created_at = models.DateTimeField(auto_now_add=True)
...
class Meta:
ordering = ['-created_at'] #created_at 속성의 역순으로 정렬한다는 의미.