Django: <QuerySet> Json 타잎으로 변환하여 리턴하는 방법

dev-swd·2020년 11월 10일
0

Python&Django

목록 보기
3/4
post-thumbnail

1. 특정 유저가 가지고 있는 다수의 게시물을 가져오면서, 각 개시물이 가지고 있는 여러장의 이미지 중 대표이미지 (가장 처음에 업로드한) 이미지만 가지고 오고 싶을 때

  • 아래와 같이 작성할 수 있다.
post_list = [
                    {
                        "post_key"        : post.post_key,
                        "post_desc"       : post.post_desc,
                        "updated_pub_date": post.updated_pub_date,
                        "first_img_url"   :
                            post.postimage_set.all().first().img_url
                    }
                    for post in posts
                ]
                
                result = {
                    user_name: {
                        "posts": post_list
                    }
                }

2. 특정 유저가 가지고 있는 다수의 게시물을 가져오면서, 각 게시물이 여러장의 이미지를 전부 가져와서 화면에 전달하고 싶을 때

  • 아래와 같이 작성할 수 있다.
post_list = [
                    {
                        "post_key"        : post.post_key,
                        "post_desc"       : post.post_desc,
                        "updated_pub_date": post.updated_pub_date,
                        "img_info"        : [{
                            "url" : post_image.img_url,
                            "id"  : post_image.pk
                        } for post_image
                             in post.postimage_set.all()]
                    }
                    for post in posts
                ]
                
                result = {
                    user_name: {
                        "posts": post_list
                    }
                }
  • 핵심은 리스트 컴프리헨션을 쓰면서 리턴 값을 딕셔너리 형태로 만들어주는 것이다.

리스트 안에 어떠한 자료 형태가 올 수 있다는 키를 캐치했다면, List Comprehension 으로 얼마든지 응용할 수 있는데.. 한 참 고민하다가 물어봤었다. 후..

profile
개발을 취미로 할 수 있는 그 때 까지

0개의 댓글