Python (with. Code)/Django-ninja

[Django Ninja] 정참조, 역참조 Schema 구현

yubi5050 2023. 4. 29. 15:59

Ninja 정참조 구현

models.py는 Comment 테이블에서 Post 테이블을 정참조

schema.py는 댓글(Comment)에서 게시글(Post) 정보를 하위 항목으로 조회 한다.

# models.py
class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField(max_length=300)

class Comment(models.Model):
    message = models.CharField(max_length=20)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)

# =====================================================
# schema.py
class PostSchema(Schema):
    title: str
    content: str
    
class CommentSchema(Schema):
    message: str
    post: PostSchema

 

Ninja 역참조 구현

역참조를 하기 위해선

models.py에서 related_name을 선언해주어야 한다. (꼭 _set이 아닌, "my_comment" 이런식으로 작성해도 가능)

schema.py에서 post에 comments를 pydantic Field의 alias인자로 related_name을 불러온다.

schema.py에서 comment에 가지고 있던 post 필드를 포함하지 않아야 한다.

# models.py
class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField(max_length=300)

class Comment(models.Model):
    message = models.CharField(max_length=20)
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="postcomment_set")
	
# =====================================================
# schema.py
class PostSchema(Schema):
    title: str
    content: str
    comments: List[CommentSchema] = Field(..., alias='postcomment_set')
    
class CommentSchema(Schema):
    message: str