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

아래 원본 글에서는 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:
```
```python
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

```
```python
id
name
email

```

Run the following commands in Django shell

```
```python
>>>qs=.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

```
```python
>>>qs=.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.

</div></div>
Share: Twitter Facebook
Bongjun Hur's Picture

About Bongjun Hur

BJ is a dev.

Seoul, Korea https://devbj.com