관리 메뉴

Storage Gonie

Django (23*) User 모델에 ManyToManyField 추가 본문

웹개발/인스타 클론 (1) Django

Django (23*) User 모델에 ManyToManyField 추가

Storage Gonie 2019. 7. 4. 11:03
반응형

아래의 작업은 users앱의 models.py에서 이뤄진다.

 

# User 모델에 followers, following 필드 추가
- followers, following 필드는 ManyToMany 관계이기 때문에 여러명의 사용자를 가질 것이고,
   User 모델에 연결될 것이므로 자신을 참조하게 되므로 "self" 속성이 들어간다.

class User(AbstractUser):

    """ User Model """
    # First Name and Last Name do not cover name patterns
    # around the globe.
    name = models.CharField(_("Name of User"), blank=True, max_length=255)

    # Constant
    GENDER_CHOICES = (
        ('male', 'Male'),
        ('female', 'Female'),
        ('not-specified', 'Not specified'),
    )

    # 확장하여 추가해줄 필드
    website = models.URLField(null=True)
    bio = models.TextField(null=True)
    phone = models.CharField(max_length=140, null=True)
    gender = models.CharField(max_length=80, choices=GENDER_CHOICES, null=True)
    followers = models.ManyToManyField("self")
    following = models.ManyToManyField("self")

    def get_absolute_url(self):
        return reverse("users:detail", kwargs={"username": self.username})

 

# DB에 반영

python manage.py makemigrations
python manage.py migrate
반응형
Comments