Meme's IT

[Django] N:M 팔로우 기능 구현 본문

BackEnd/Django

[Django] N:M 팔로우 기능 구현

Memez 2023. 10. 17. 10:19

User(M) : User(N)

여기서는 테이블이 한개!!

# accounts/models.py

class User(AbstractUser):
    followings = models.ManyToManyField('self',symmetrical=False, related_name='followers')

자기 자신과 다대다 관계 → 'self'

symmetrical → 대칭(기본값은 True), 여기서 안쓰면 자동으로 맞팔시킴

related_name → 역참조시 사용하는 이름 이걸 이용해서 역참조할때 user.followers.all()으로 조회할 수 있다

 

# accounts/urls.py

urlpatters = [
	...
    path('<int:user_pk>/follow',views.follow,name="follow"),
]
# accounts/views.py

def follow(request, user_pk):
    User = get_user_model()
    you = User.objects.get(pk = user_pk)
    me = request.user
    
    if me != you:
        # 내가 상대방의 팔로워 목록에 있다면
        if me in you.followers.all():
            # 팔로우 취소
            you.followers.remove(me)
            # me.following.remove(you)  둘 다 똑같음
        else:
            you.followers.add(me)
            # me.following.add(you) 둘 다 똑같음
    return redirect('accounts:profile', you.username)   
    # 팔로하면 팔로우한 대상의 프로필로 감

 

profile.html에서 팔로우 버튼 만들기

<!-- profile.html user의 프로필 밑에 추가 -->

<div>
    <div>
        팔로잉  : {{ person.followings.all|length }} / 팔로워 : {{ person.followers.all|length }}
    </div>
    {% if request.user != person %}
        <div>
            <form action="{% url "accounts:follow" person.pk %}" method="POST">
                {% csrf_token %}
                {% if request.user in person.follwers.all %}
                    <input type="submit" value="언팔로우">
                {% else %}
                    <input type="submit" value="팔로우">
                {% endif %}
            </form>
        </div>
    {% endif %}
</div>

다른사람 프로필 갔을 때

내 프로필

'BackEnd > Django' 카테고리의 다른 글

[Django] Query  (0) 2023.10.17
[Django] Fixtures  (0) 2023.10.17
[Django] N:M 프로필 만들기  (0) 2023.10.17
[Django] 웹 크롤링(Web Crawling)  (0) 2023.10.13
[Django] 로그인(5) 로그인 후, 페이지 다르게 출력하기  (0) 2023.10.05