Web개발/DJANGO
Django : Common Model활용하기
별냥이
2020. 7. 7. 00:26
반응형
출처 :
www.andrew-tremblay.com/blog/django-common-models/
흔히 모델 작업을 하다보면, 다음과 같은 내용들을 처리하는데 어려움을 겪는다.
- 오브젝트의 unique identifier : id
- 오브젝트 생성시점 : created_at
- 오브젝트 생성한 유저 : created_by
- 오브젝트 업데이트 시점 : updated_at
- 오브젝트 업데이트한 유저 : updated_by
해당 내용은 이미 Django의 기본 Model에 들어가있으며(Common Model) 다음과 같이 사용할 수 있다.
1
2
3
4
5
6
7
8
9
10
|
class Application(models.Model):
property = models.ForeignKey(Property, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='applications', editable=False, null=True)
...
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
if not self.user:
self.user = self.created_by
super(Application, self).save(*args, **kwargs)
|
반응형