TIL_231024_ManyToManyField

Sol Lee·2023년 10월 24일
1

ManyToManyField 사용하기

팀프로젝트 진행중. 같이 밥먹을 사람을 구하는 서비스를 만드려고 함.

한 유저가 밥친구를 구하는 글을 올리면 올려진 글에 여러 유저가 연결되는 식으로 구현하고자 함.

작성자와 다른 사용자가 put 요청을 보낼 경우 생성한 ManyToManyField에 아이디가 추가되도록 하고 싶었음.

ManyToManyField 생성

# article의 models.py

...
friends_ids = models.ManyToManyField('user.User', related_name='user_friend', blank=True)

마이그레이션을 해주면 article_article_friends_ids라는 이름으로 아래와 같은 테이블이 생성됨.

ManyToManyField 값 추가하기 = add()

#예시: <object>.<m2m 필드명>.add(<추가할 값>)
article.friends_ids.add(request.user)
# 작성 코드
	except ObjectDoesNotExist
			# 작성자 이외의 사람의 요청이고 새로 등록 되었을 때
			article.friends_ids.add(request.user)
			return Response({'message':'밥친구로 등록되었습니다.'}, status=status.HTTP_200_OK)

article과 user 를 연결하는 m2m 필드

💡 friends_ids = models.ManyToManyField('user.User', related_name='user_friend', blank=True)

  1. 연결 되어있는 (user_id) 값에 접근하고 싶을 때 = m2m 필드명 사용
# 예시: 해당 아티클의 m2m 값 중에 요청자와 같은 id가 있는지 찾고 싶을 때
article.friends_ids.get(id=request.user.id)
# 작성 코드
article = get_object_or_404(Article, id=article_id)
if request.user == article.author_id:
...
else:
	try:
			# 작성자 이외의 사람의 요청이지만 이미 등록된 사람일 때
			article.friends_ids.get(id=request.user.id)
			return Response({'message':'이미 밥친구로 등록되어 있습니다.'}, status=status.HTTP_409_CONFLICT)
	except ObjectDoesNotExist:
			# 작성자 이외의 사람의 요청이고 새로 등록 되었을 때
			article.friends_ids.add(request.user)
			return Response({'message':'밥친구로 등록되었습니다.'}, status=status.HTTP_200_OK)
  1. 연결한 값(article_id)에 접근 하고 싶을때 = related_name 사용
# 예시: article값이 같은 m2m 필드를 전부 불러오고 싶을 때
User.objects.filter(user_friend=article.id)
# 작성 코드
def get_member_count(self, article):
        """ 해당 게시글에 등록된 밥친구 몇명인지 반환 """
        member_count = len(User.objects.filter(user_friend=article.id))
        return member_count
profile
직업: 개발자가 되고 싶은 오레오 집사

1개의 댓글

comment-user-thumbnail
2023년 10월 25일

주석으로 코드 설명이 되어 있어 코드 이해가 쉽네요~

답글 달기