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

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?


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')

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.


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()