[Django] property 데코레이터로 외래키 참조 데이터 가져오기

고등어찌짐·2022년 5월 17일
0

Web

목록 보기
1/1
post-thumbnail

보통 사용하는 외래키 참조 방식이 아닌 property 데코레이터를 사용해 외래키 참조 데이터를 가져오는 방법을 회고한다.


1. 보통의 참조 방법

장고 개발을 하다보면 외래키를 참조해야하는 일이 생긴다.

Reporter 와 Rerporter 를 외래키 참조하는 Article 테이블이 있다고 가정하자.

# models.py
class Reporter(models.Model):
    id = models.CharField(max_length=30)
    email = models.EmailField()
    
class Article(models.Model):
    reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)
    headline = models.CharField(max_length=100)
    pub_date = models.DateField()

이때 특정 id 을 가지는 reporter 의 Article object 들을 가지고 싶다면, 다음과 같이 코드를 작성한다.

# views.py
article_obj = Article.objects.filter(...)
my_id = article_obj.reporter.id

2. @property 참조 방법

그런데 이렇게 개발하다보니 다음과 같은 문제가 생겼다.

  • RDB 관계를 모르거나 django 와 친숙하지 않은 개발자와 협업할 때
  • 외래키 참조가 2중, 3중 으로 깊어지고 코드가 길어지고 가독성이 떨어짐

특히 2번째 경우에서 myobj.aaa_fk.bbb_fk.ccc_fk.myfield 와 같은 현상이 일어났는데, property decorator 로 깔끔하게 데이터를 가져올 수 있었다. @property 를 사용하면 자세한 구현 코드를 보이지 않고도 클래스 내의 필드 접근 방식을 바꿀 수 있기 때문이다.

먼저 다음과 같이 외래키 참조할 테이블에 property method 를 추가로 작성한다.

# models.py
class Reporter(models.Model):
    id = models.CharField(max_length=30)
    email = models.EmailField()

class Article(models.Model):
    reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)
    headline = models.CharField(max_length=100)
    pub_date = models.DateField()
    
    @property
    def id:
    	return self.reporter.id
    

그러면 다음처럼 간단하게 id 를 가져올 수 있다.

# views.py
my_id = article_obj.id
    

Django documet Many-to-one relationships
https://docs.djangoproject.com/en/4.0/topics/db/examples/many_to_one/
Django - get data from foreign key
https://stackoverflow.com/questions/43187327/django-get-data-from-foreign-key
Get Data From A Foreign Key Django
https://stackoverflow.com/questions/66811414/get-data-from-a-foreign-key-django

profile
플로우를 타자🌊

0개의 댓글