Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

django

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?

like image 394
user1881957 Avatar asked Jan 22 '13 10:01

user1881957


People also ask

Can I filter a QuerySet Django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.

How you combine multiple QuerySet in a view?

Use union operator for queryset | to take union of two queryset. If both queryset belongs to same model / single model than it is possible to combine querysets by using union operator. One other way to achieve combine operation between two queryset is to use itertools chain function.

Which can be used to retrieve an object directly instead of a QuerySet?

Retrieving Single Objects from QuerySets We can do this using the get() method. The get() returns the single object directly. Let's see the following example. As we can see in both examples, we get the single object not a queryset of a single object.


1 Answers

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') 
like image 182
Rohan Avatar answered Sep 23 '22 14:09

Rohan