ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Django Signal 사용하기
    Django 2021. 9. 8. 22:38
    SMALL

    profiles App 에 두 개의 모델이 있다. User 와 Profile 두 개는 항상 ForeignKey로 연결되어 있다.

    User 가 회원가입할 때마다 Profile 항상 어떻게 연결시킬까?

    
    class Profile(models.Model):
        user_profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
        about = models.CharField(max_length=120)
        created_at = models.DateTimeField(auto_now=True)
        updated_at = models.DateTimeField(auto_now=True)

     

    물론 Views.py에서 회원가입할 때 custom 해서 Profile 모델을 만들고 연결시킬 수 있지만 더 좋은 방법은 signal을 사용하는 방법이다. (위 경우 말고 다른 경우에도 쓰일 수 있고 한번 만들어두면 다른 view에도 적용됨 매번 다른 view에 같은 걸 코딩할 필요가 없다.)

     

    user app 에 signals.py 을 만든다. 

    from django.contrib.auth.models import User
    from django.db.models.signals import post_save
    from django.dispatch import receiver
    from profiles.models import Profile
    
    @receiver(post_save, sender=User)
    def create_profile(sender, instance, created, **kwargs):
        print('created: ', created)
        if created:
            Profile.objects.create(user=instance)

    @receiver에 post_save 말고 post_delete 도 넣을 수 있다. sender에는 기준 모델을 넣는다.
    위 내용은 User 가 생성되었을 때, Profile 오브젝트를 만든다.
    마지막으로 profiles app에 __init__.py 와 apps.py를 아래와 같이 수정한다.

    __init__.py
    
    default_app_config = 'profiles.apps.ProfilesConfig'
    
    
    apps.py
    
    
    from django.apps import AppConfig
    
    class ProfilesConfig(AppConfig):
        name = 'profiles'
    
        def ready(self):
            import profiles.signals

    어떤 모델이 어떤 값이 특정 값으로 변할 때 동작되는 함수나, 어떤 모델이 삭제될 때 동작되는 함수를 signal을 통해서 적용할 수 있다. 진짜 앞으로 많이 쓰게 될 거 같고 이미 만든 프로젝트에도 많이 적용할 듯 ㅠㅠ 다시 코딩해야 돼

     

     

    BIG

    'Django' 카테고리의 다른 글

    django SASS/SCSS 적용하기  (0) 2021.08.21

    댓글

Designed by Tistory.