Ali Husham
Ali Husham

Reputation: 936

How to get list of fields instead of one field in `Mymodel.objects.values()`

in Django models you can filter the field that you want but how to get a list of fields instead of one field.

print(list(MyModel.objects.all()))
# returns this [<ChangeTrack: ChangeTrack object (1)>, <ChangeTrack: ChangeTrack object (2)>, <ChangeTrack: ChangeTrack object (3)>,]

print(list(MyModel.objects.values('id')))
#returns this [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}, {'id': 5}, {'id': 6}, {'id': 7}, {'id': 8}, {'id': 9}, ]

# I want to use `request.GET.get('fields')` in django views
print(list(MyModel.objects.values(request.GET.get('fields')))
print(list(MyModel.objects.values('id', 'username')))
# to return [{'id': 1,'username':'ali'}, {'id': 2,'username':'jack'}, {'id': 3,'username':'any'}, {'id': 4,'username':'more'}, {'id': 5,'username':'john'}, ... ]

error django.core.exceptions.FieldError: Cannot resolve keyword 'id,username' into field. Choices are: action_type, by, by_id, date_created, deleted, field_target, field_value, id, model_target, username, related_to, related_to_id

Upvotes: 0

Views: 545

Answers (3)

Abdul Aziz Barkat
Abdul Aziz Barkat

Reputation: 21792

From your error Cannot resolve keyword 'id,username' I can see that you send comma separated field names in the GET parameter fields. You can use the steps below to do what you want:

  1. Split the string on commas and make it a list. Also strip any potential spaces just for good measure:

    field_names = []
    if 'fields' in request.GET:
        field_names = [i.strip() for i in request.GET.get('fields').split(',')]
    
  2. Pass these field_names to .values by using unpacking:

    print(list(MyModel.objects.values(*field_names)))
    

Note: This can give you errors considering the user may pass incorrect field names. You might want to consider using Form classes and using MultipleChoiceField [Django docs]

Upvotes: 1

Alexander Yudkin
Alexander Yudkin

Reputation: 472

You can pass needed sequence of fields to the value method like this:

MyModel.objects.values('id', 'username')

Also take a look at the values_list and only methods, them could be useful too.

https://docs.djangoproject.com/en/3.2/ref/models/querysets/#values-list

Upvotes: 1

Jeet Patel
Jeet Patel

Reputation: 1241

You can achieve it like this -

MyModel.objects.values('id', 'username').all()

all() method of model manager will return the list of all the objects like -

[{'id': 1,'username':'ali'}, {'id': 2,'username':'jack'}, {'id': 3,'username':'any'}, {'id': 4,'username':'more'}, {'id': 5,'username':'john'}, ... ]

Upvotes: 0

Related Questions