개발 작업시에 사용한 검색어, 내용을 간단하게 정리하고, 다양한 인터넷 정보, 팁, 저장하고 싶은 소스등을 대충 정리해 두는 개인 블로그 입니다. 힌트나 도움이 되는 글이 조금이라도 있기를 바라며 🙂

Django QuerySet 리스트, 딕셔너리 변환

Written in

by

아래 원본 글에서는 model_to_dict 사용해서 excludes 이런것도 해결되어 있는데,
에러가 나서 그냥 fields 만 해서 리턴하는 함수로 변경
# Note: Usage
# queryset_to_list(releases, [“is_success”, “done_count”])
def queryset_to_list(qs, fields=None):
    if fields:
        qs = qs.values(*fields)
    return list(qs)

참고 사이트

https://stackoverflow.com/questions/7811556/how-do-i-convert-a-django-queryset-into-list-of-dicts

You could define a function using model_to_dict as follows:
from django.forms.models import model_to_dict
def queryset_to_list(qs,fields=None, exclude=None):
    return [model_to_dict(x,fields,exclude) for x in qs]

Suppose your Model has the following fields

id
name
email

Run the following commands in Django shell

>>>qs=<yourmodel>.objects.all()
>>>list=queryset_to_list(qs)
>>>list
[{'id':1, 'name':'abc', 'email':'abc@ab.co'},{'id':2, 'name':'xyz', 'email':'xy@xy.co'}]

Say you want only the id and the name in the list of queryset dictionary

>>>qs=<yourmodel>.objects.all()
>>>list=queryset_to_list(qs,fields=['id','name'])
>>>list
[{'id':1, 'name':'abc'},{'id':2, 'name':'xyz'}]

Similarly, you can exclude fields in your output.


최근 블로그 글…

  • ORM 중복 제거 – distinct

    https://django-orm-cookbook-ko.readthedocs.io/en/latest/duplicate.html 여기 링크 글이 좋음 – https://unocoings.tistory.com/12

  • Django – AWS Cognito 연동 예제 글 (초안)

    Django – AWS Cognito 연동 예제 만들어 보기 – 초안 안녕하세요. 오늘은 장고(Django) 웹 프레임워크와 AWS Cognito 서비스를 연동하는 예제를 소개하겠습니다. Cognito는 AWS에서 제공하는 사용자 인증 및 권한 관리 서비스입니다.…

  • 발표자료 준비 팁

    머리 아픈 발표자료, 아래 링크 글을 참고해서 준비해보세요. 04화 발표 자료 준비하는 게 어렵다고? 자, 따라 해 봐 (brunch.co.kr) 이 글은 발표 자료를 준비하는 방법에 대한 팁을 제공하는 글입니다. 저자는…

  • Django Ninja 개발 블로그 추천

    Django ninja 사용자가 별로 없어 보이는데, 꼭 링크를 저장해두고 보자! 잘 정리해둔 사이트 https://yubi5050.tistory.com/category/Python%20%28with.%20Code%29/Django-ninja [Django Ninja] Validation 구현 방법 (with. Pydantic) [Django Ninja] 설계 패턴 정하기 (feat. 리팩토링) [Django Ninja]…

  • Django – HttpResponse() 예제

    간단한 결과 확인을 위한 HttpResponse 예제를 하나 정리해둔다. 공식 사이트는 여기 => https://docs.djangoproject.com/en/4.2/ref/request-response/#httpresponse-objects

  • Xilinx JTAG – HS2, HS3, Platform Cable USB II

    JTAG HS2 가 호환성이 더 좋은듯 https://digilent.com/reference/programmers/jtag-hs2/reference-manual?_ga=2.209894997.1913691520.1700123539-2102363698.1698815413#supported_target_devices Is JTAG-HS2 is compatible with Artix 7 series FPGA? Digilent Forumhttps://forum.digilent.com › … › FPGA Nov 9, 2022 — Is JTAG-HS2 is compatible with Artix 7 series FPGA? 1 answer·0…

aws Blog css database develop Django embedded file FPGA frontend html javascript jquery KiCad ModelForm Nextion ninja none ORM postgresql python Queryset redirect replace sql STM32 stm32f407 template TTA uart updateview Wordpress Xilinx 날짜 데이터베이스 딕셔너리 리스트 배열 시험 예제 인증 전역변수 조건 파이썬 한글