[DRF] Issue Report - ManyToManyField์™€ related_name

Yungsang Hwangยท2022๋…„ 7์›” 12์ผ
0

Django-Rest-Framework

๋ชฉ๋ก ๋ณด๊ธฐ
5/15
post-thumbnail

Issue Report - ManyToManyField์™€ related_name


๐Ÿšฉ์ƒํ™ฉ

  • ์‚ฌ์šฉ์ž๊ฐ€ ์งˆ๋ฌธ๊ธ€๊ณผ ๋‹ต๊ธ€์„ ์ž‘์„ฑํ•˜๋ฉด, ๋‹ค๋ฅธ ์‚ฌ์šฉ์ž๋Š” ์ข‹์•„์š”๋ฅผ ๊ฐ๊ฐ ์งˆ๋ฌธ๊ธ€๊ณผ ๋‹ต๊ธ€์— ์ƒํ˜ธ์ž‘์šฉํ•  ์ˆ˜ ์žˆ์Œ
  • ๊ทธ๋ ‡๊ธฐ ๋•Œ๋ฌธ์— ์งˆ๋ฌธ๊ธ€๊ณผ ๋‹ต๊ธ€์— ๊ฐ๊ฐ ์ข‹์•„์š” ํ•„๋“œ๊ฐ€ ํ•„์š”ํ•จ
  • ์‚ฌ์šฉ์ž-์งˆ๋ฌธ๊ธ€ ํ…Œ์ด๋ธ”์— M:M์œผ๋กœ ์—ฐ๊ฒฐ๋˜๋Š” ์งˆ๋ฌธ๊ธ€ ์ข‹์•„์š” ํ…Œ์ด๋ธ”๊ณผ ์‚ฌ์šฉ์ž-๋‹ต๊ธ€ ํ…Œ์ด๋ธ”์— M:M์œผ๋กœ ์—ฐ๊ฒฐ๋˜๋Š” ๋‹ต๊ธ€ ์ข‹์•„์š” ํ…Œ์ด๋ธ”์„ ๊ฐ๊ฐ ์ƒ์„ฑํ•˜๊ณ  ์‹ถ์Œ
  • ERD ๋Œ€๋กœ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•˜๊ณ , migrations์„ ํ•˜๋Š” ์ค‘ ํ•˜๊ธฐ์™€ ๊ฐ™์€ ์˜ค๋ฅ˜์ฝ”๋“œ๋ฅผ ๋ฑ‰์–ด๋ƒˆ๋‹ค.

class QnAQuestion(models.Model):
    user = models.ForeignKey(UserModel, verbose_name="์งˆ๋ฌธ์ž‘์„ฑ์ž", on_delete=models.CASCADE)
    title = models.CharField("์ œ๋ชฉ", max_length=100)
    content = models.TextField("์งˆ๋ฌธ๊ธ€")
    like = models.ManyToManyField(UserModel, through="QuestionLike")
    created_at = models.DateTimeField("์ƒ์„ฑ์‹œ๊ฐ„", auto_now_add=True)
    updated_at = models.DateTimeField("์ˆ˜์ •์‹œ๊ฐ„", auto_now=True)

    def __str__(self):
        return f"์ž‘์„ฑ๋œ ์งˆ๋ฌธ์€ {self.title} ์ž…๋‹ˆ๋‹ค"
  • ์ž‘์„ฑ๋œ ERD๋Œ€๋กœ ManyToMany ํ•„๋“œ๋ฅผ ์ž‘์„ฑํ•˜๋ ค๊ณ  ํ•˜์ž ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•˜๋ฉด์„œ ๋งˆ์ด๊ทธ๋ ˆ์ด์…˜์ด ์‹คํ–‰๋˜์ง€ ์•Š์•˜์Œ

๐Ÿšฉ์˜ค๋ฅ˜์ฝ”๋“œ

๐ŸšฉํŠธ๋Ÿฌ๋ธ”์ŠˆํŒ…

์ ํ”„ ํˆฌ ํŒŒ์ด์ฌ

  • ๊ตฌ๊ธ€๋ง์„ ํ†ตํ•ด ๋ฌธ์ œ์˜ ๋‚ด์šฉ์„ ์ฐพ์•„๋ณด๋‹ˆ QnAQuestion ๋ชจ๋ธ์—์„œ ์‚ฌ์šฉํ•œ user์™€ like ํ•„๋“œ๊ฐ€ ๋ชจ๋‘ UserModel๊ณผ ์—ฐ๊ฒฐ์ด ๋˜์–ด์žˆ์–ด์„œ ์ƒ๊ธด ๋ฌธ์ œ
  • UserModel.qnaquestions_set์ฒ˜๋Ÿผ User๋ชจ๋ธ์„ ํ†ตํ•ด์„œ ๋ฐ์ดํ„ฐ์— ์ ‘๊ทผํ•˜๋ ค ํ• ๋•Œ user๋ฅผ ๊ธฐ์ค€์œผ๋กœ ํ• ์ง€, like๋ฅผ ๊ธฐ์ค€์œผ๋กœ ํ•ด์•ผํ• ์ง€ ๋ช…ํ™•ํ•˜์ง€ ์•Š๋‹ค๋Š” ๊ฒƒ์ด ์ด์œ ์˜€๋‹ค

๐Ÿšฉํ•ด๊ฒฐ

ํ•˜๋‚˜์˜ ๋ชจ๋ธ์—์„œ ์ฐธ์กฐํ•˜๊ณ  ์žˆ๋Š” ์œ ์ €๋ชจ๋ธ์ด ๋‘ ๊ฐœ๋‚˜ ์žˆ๋‹ค!

  • ERD์˜ ์„ค๊ณ„ ์ƒ์œผ๋กœ๋Š” ๋ฌธ์ œ๊ฐ€ ์—†์—ˆ์œผ๋‚˜ ๋ฌผ๋ฆฌ์ ์œผ๋กœ ๋ชจ๋ธ์„ ์ƒ์„ฑํ•  ๋•Œ ๊ฐ ํ•„๋“œ๊ฐ€ ์ฐธ์กฐํ•˜๊ณ  ์žˆ๋Š” ๋ชจ๋ธ์ด ๋™์ผํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๋ฐœ์ƒํ•œ ๋ฌธ์ œ
  • ๊ทธ๋Ÿฌ๋‚˜ ๋ชจ๋ธ์„ ์ƒ์„ฑํ•˜๋Š” ๊ณผ์ •์—์„œ ๋ฐœ์ƒํ•œ ๋ฌธ์ œ๋กœ, ์ด๋Š” ํ•˜๋‚˜์˜ ๋ชจ๋ธ์ด ์—ญ์ฐธ์กฐํ•  ๋•Œ ๋ฐ”๋ผ๋ด์•ผํ•  ํ•„๋“œ๊ฐ€ ๋ฌด์—‡์ธ์ง€ ํ™•์‹คํ•˜๊ฒŒ ์ •์˜ํ•ด์ค˜์•ผ ํ•œ๋‹ค
  • ManyToMany ํ•„๋“œ์— related_name์„ ์ง€์ •ํ•ด์ฃผ๋Š” ๊ฒƒ์œผ๋กœ ์ถฉ๋Œ์„ ํ”ผํ•  ์ˆ˜ ์žˆ๋‹ค.(๋‹ค๋ฅธ ํ•„๋“œ์—์„œ๋„ ๊ฐ€๋Šฅํ•˜์ง€๋งŒ, ์ด๋ฆ„์„ ๊ตณ์ด ์ถ”๊ฐ€์ ์œผ๋กœ ๋ฐ”๊ฟ”์ฃผ์ง€๋Š” ์•Š์•˜๋‹ค)
like = models.ManyToManyField(UserModel, related_name='question_like', through="QuestionLike")
profile
ํ•˜๋ฃจ์ข…์ผ ๋ชฝ์ƒ๊ฐ€

0๊ฐœ์˜ ๋Œ“๊ธ€