-
django managers.pyProject using python/Cloning Airbnb 2021. 3. 3. 15:07
설명
model의 objects를 customizing 할 수 있다.
user model 따로 나머지 model(core) 따로 만들었다. 왜냐하면 user model은 AbstractUser를 상속하는 반면에 나머지 model은 model.Model을 상속하기 때문이다.
get_or_none은 models.<model_name>.obejcts.get()에서 생기는 error(예를 들어, models.User.DoesNotExist)를 더 간편히 처리하기 위해 만들어졌다. DoesNotExist 에러대신 None을 반환하는 형식이다.
# users/managers.py from django.contrib.auth.models import UserManager as AbstractUserManager class CustomUserModelManager(AbstractUserManager): def get_or_none(self, **kwargs): try: return self.get(**kwargs) except self.model.DoesNotExist: return None
# core/managers.py from django.db import models class CustomModelManager(models.Manager): def get_or_none(self, **kwargs): try: return self.get(**kwargs) except self.model.DoesNotExist: return None
models.py
다음은 각각의 model의 objects에 추가된 code다.
# users/models.py from . import managers class User(AbstractUser): objects = managers.CustomUserModelManager()
# core/models.py from . import managers class TimeStampedModel(models.Model): objects = managers.CustomModelManager()
참고 자료
- 노마드 코더의 Airbnb 클론 강의
- Custom managers
소스 코드
github.com/zpskek/airbnb-clone-v3/commit/c66bd260ff866ae99a3413ea49d0339650469806
'Project using python > Cloning Airbnb' 카테고리의 다른 글
django mailgun.com 연동(interlocking) (0) 2021.03.04 django kakao login (0) 2021.03.03 django github login (0) 2021.03.03 django messages framework (0) 2021.03.02 Using the Django authentication system (0) 2021.03.02