My Profile Photo

DongChanS's blog


수학과 학생의 개발일지


인스타 클론코딩 2, Posts앱 (2) - 특정 유저의 포스트 작성

1) Posts App

1-1. OverView

  1. Post 모델 작성

    • Post는 특정 유저의 소유물이 되게 하고싶음.

      => 1:N relation

  2. 1:N relation

    • ForeignKey
    • 두 테이블을 연결하는 방법

1-2. Post와 유저를 연결

  1. 유저들의 정보를 담는 데이터베이스

    from django.contrib.auth.models import User
    from django.conf import settings # settings.AUTH_USER_MODEL
    from django.contrib.auth import get_user_model
    

    Django에서 따로 지원하며, 불러올 수 있는 방법은 3가지가 있다.

    1. User
      • Django에서 지원하는 User 클래스
    2. settings.AUTH_USER_MODEL
      • (기본값) User 클래스와 연결되어있음
      • (Custom) User 클래스를 새롭게 커스터마이징하면, 이 클래스와 연결할 수 있음.
    3. get_user_model()
      • settings.AUTH_USER_MODEL을 리턴하는 함수
  2. User 클래스와 Post 클래스의 관계

    • 유저 한명은 여러개의 포스트를 소유가능함.
    • 포스트 하나는 오직 하나의 유저에만 소속됨

    => 이러한 경우에는 1:N relation을 적용하는게 좋다.

2) 1:N relations (many-to-one relationship)

2-1. 설명

위키피디아 참고

In a relational database, a one-to-many relationship exists when one row in table A may be linked with many rows in table B, but one row in table B is linked to only one row in table A. It is important to note that a one-to-many relationship is not a property of the data, but rather of the relationship itself.

A list of authors and their books may happen to describe books with only one author, in which case one row of the books table will refer to only one row of the authors table, but the relationship itself is not one-to-many, because books may have more than one author, forming a many-to-manyrelationship.

만약 포스트 하나가 여러 유저에게서 작성될 수 있다면 M:N 관계를 적용해야하지만, 인스타그램은 한명만 관여하므로 1:N 관계를 적용하면 된다.

이 경우에는 포스트가 N이고, 유저가 1입니다. ( 한명의 유저 -> 여러 개의 포스트 )

2-2. 구현되는 방식

각 유저마다 작성한 포스트들의 id를 기록하는 것보다는, 각각의 포스트를 소유하는 유저의 id를 기록하는게 편하다.

=> Post 테이블에서 user_id 컬럼을 추가해서 누가 작성했는지 알려주면 된다.

Content Image user_id
첫글 /media/kermit1.jpg 1
첫글 /media/kermit2.jpg 2
두번째글 /media/cat1.jpg 1
자기소개 /media/self1.jpg 3

2-3. Django를 활용하기

위의 user_id 컬럼 역할을 Django의 ForeignKey 필드를 통해서 만들 수 있다.

  1. Definition

    ForeignKey ( to = 상대 테이블, on_delete = 삭제옵션)

    • to : 유저 클래스 => get_user_model()
    • on_delete : 유저 한명이 회원탈퇴하면 그 유저의 포스트는 어떻게 할 것이냐?
      • 보통 전부 삭제되는 편이 좋다. => models.CASCADE
  2. Models.py

    from django.contrib.auth import get_user_model
       
    class Post(models.Model):
        content = models.CharField(max_length=100)
        image = models.ImageField(blank=True)
        user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
    

2-4. 두 테이블을 연결하는 방법

post : 특정 포스트 객체

user : 특정 유저 객체

  1. post.user_id

    • 포스트를 가진 유저의 아이디
  2. post.user

    • 포스트를 가진 유저객체
  3. user.post_set.all()

    • 유저가 가지고 있는 포스트들의 집합

      => Django에서는 이것도 지원해주기 때문에 1:N 관계를 다루기 매우 편리하다.

comments powered by Disqus