How to get a particular attribute from queryset in Django in view?

Django

Django Problem Overview


I have a query like this:

file_s = Share.objects.filter(shared_user_id=log_id)

Now, I want to get the files_id attribute from file_s in Django view. How can I do that?

Django Solutions


Solution 1 - Django

Use values() to get particular attribute which will return you list of dicts, like

file_s = Share.objects.filter(shared_user_id=log_id).values('files_id')

EDIT: If you want only one attribute then you can use flat=True to suggest to return just list of values. However, make sure in what order the list will be.

file_s = Share.objects.filter(shared_user_id=log_id).values_list('files_id', flat=True).order_by('id')

Solution 2 - Django

Your Share.objects.filter() call returns a Djagno QuerySet object which is not a single record, but an iterable of filtered objects from the database with each item being a Share instance. It's possible that your filter call will return more than one item.

You can iterate over the QuerySet using a loop such as:

for share in files_s:
    print share.files_id

If you know that your query is only expected to return a single item, you could do:

share = Share.objects.get(shared_user_id=log_id)

which will return a single Share instance from which you can access the files_id attribute. An exception will be raised if the query would return anything other than 1 result.

Solution 3 - Django

If you want to get only the value from a single value QuerySet you can do:

file_s = Share.objects.filter(shared_user_id=log_id).values_list('files_id', flat=True).first()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1881957View Question on Stackoverflow
Solution 1 - DjangoRohanView Answer on Stackoverflow
Solution 2 - DjangoAustin PhillipsView Answer on Stackoverflow
Solution 3 - Djangoddns1002View Answer on Stackoverflow