course_qs = <whatever query gave you the queryset>
for course in course_qs:
print(course['course_code'])
Use this
someTable.objects.all()[0]['course_code']
or
someTable.objects.values_list('course_code', flat = True)
courses = <your query set>
print(courses[0]['course_code'])
Now is much easier than before. for instance, you can use:
obj = Model.objects.all().first() # { 'course_code': 11 } course_code = obj.course_code # 11
What worked for me:
course_qs = <whatever query gave you the queryset>
list_of_course = list(course_qs)
You can try the following which will return a list of values from the queryset.
courses = <your query set>
linked_content = []
for content in courses:
linked_content.append(content)
return linked_content
The values() method allows you to return each object as a Python dictionary, with the names and values as key/value pairs:,The values_list() method allows you to return only the columns that you specify.,You can filter the search to only return specific rows/records, by using the filter() method.,You will learn more about the filter() method in the next chapter.
members/views.py
:
from django.http
import HttpResponse
from django.template
import loader
from.models
import Members
def testing(request):
mydata = Members.objects.all().values()
template = loader.get_template('template.html')
context = {
'mymembers': mydata,
}
return HttpResponse(template.render(context, request))
members/views.py
:
from django.http
import HttpResponse
from django.template
import loader
from.models
import Members
def testing(request):
mydata = Members.objects.values_list('firstname')
template = loader.get_template('template.html')
context = {
'mymembers': mydata,
}
return HttpResponse(template.render(context, request))
members/views.py
:
from django.http
import HttpResponse
from django.template
import loader
from.models
import Members
def testing(request):
mydata = Members.objects.filter(firstname = 'Emil').values()
template = loader.get_template('template.html')
context = {
'mymembers': mydata,
}
return HttpResponse(template.render(context, request))
The query parameter to QuerySet exists so that specialized query subclasses can reconstruct internal query state. The value of the parameter is an opaque representation of that query state and is not part of a public API.,Returns a QuerySet that evaluates to a list of datetime.datetime objects representing all available dates of a particular kind within the contents of the QuerySet.,Returns a QuerySet that evaluates to a list of datetime.date objects representing all available dates of a particular kind within the contents of the QuerySet.,The additional queries in prefetch_related() are executed after the QuerySet has begun to be evaluated and the primary query has been executed.
for e in Entry.objects.all():
print(e.headline)
async
for e in Entry.objects.all():
results.append(e)
entry_list = list(Entry.objects.all())
if Entry.objects.filter(headline = "Test"):
print("There is at least one Entry with the headline Test")
>>> import pickle >>> query = pickle.loads(s) # Assuming 's' is the pickled string. >>> qs = MyModel.objects.all() >>> qs.query = query # Restore the original 'query'.
>>> import pickle
>>> qs = Blog.objects.values_list('id', 'name')
>>> qs
<QuerySet [(1, 'Beatles Blog')]>
>>> reloaded_qs = Blog.objects.all()
>>> reloaded_qs.query = pickle.loads(pickle.dumps(qs.query))
>>> reloaded_qs
<QuerySet [{'id': 1, 'name': 'Beatles Blog'}]>
So that means we create a QuerySet of singular values, and we then will retrieve the last entry of that queryset. Note that we do not fetch all the elements from the queryset, the .last() is "injected" in the query we perform on the database, so the result is the scalar value of that column for the last record.,If you only pass in a single field, you can also pass in the flat parameter. If True, this will mean the returned results are single values, rather than one-tuples.,The problem here is that your .last() will retrieve the last Settings object. You thus will call .values('bb_bonus') on the Settings object. Since a model has no .values(..) method, it will thus not return anything.,We here thus use .values_list(..) [Django-doc], this accepts the names of the columns as parameters. It will then usually return a QuerySet of lists with these values. But if you specify one column; then, as the documentation says:
You can however retrieve the value of a certain column from a queryset, with:
Settings.objects.values_list('bb_bonus_qualify', flat = True).last()
AFAIK __str__
has nothing to do with .values()
- the problem here is that you need to specify the values before getting a specific item, rather than the other way round:
Settings.objects.values('bb_bonus').last()
Say, we want to get first_name and last_name of all the users whose name starts with R. You do not want the fetch the other fields to reduce the work the DB has to do.,values and values_list methods on queryset.,Django provides two ways to do this,The auth_user model has a number of fields in it. But sometimes, you do not need to use all the fields. In such situations, we can query only desired fields.
>>> queryset = User.objects.filter(
first_name__startswith = 'R'
).values('first_name', 'last_name') >>>
queryset <
QuerySet[{
'first_name': 'Ricky',
'last_name': 'Dayal'
}, {
'first_name': 'Ritesh',
'last_name': 'Deshmukh'
}, {
'first_name': 'Radha',
'last_name': 'George'
}, {
'first_name': 'Raghu',
'last_name': 'Khan'
}, {
'first_name': 'Rishabh',
'last_name': 'Deol'
}]
SELECT "auth_user".
"first_name", "auth_user".
"last_name"
FROM "auth_user"
WHERE "auth_user".
"first_name"::text LIKE R %
>>> queryset = User.objects.filter(
first_name__startswith = 'R'
).only("first_name", "last_name")
SELECT "auth_user".
"id", "auth_user".
"first_name", "auth_user".
"last_name"
FROM "auth_user"
WHERE "auth_user".
"first_name"::text LIKE R %
Now that we understand the basics of using filter() and exclude() to retrieve a modified QuerySet in Django, we can use these methods to look for field values that are either empty or NULL.,There we have it! Some simple uses of filter() and exclude() to retrieve (or ignore) both NULL and empty values in Django QuerySets.,Now, by using filter(), we can retrieve a QuerySet of just those books that were published within the last 90 days period, like so:,Easily the most important method when working with Django models and the underlying QuerySets is the filter() method, which allows you to generate a QuerySet of objects that match a particular set of filtered parameters.
name__contains = 'Smith'
>>> Book.objects.count() 20
>>> from datetime
import datetime, timedelta
>>>
Book.objects.filter(date_published__gte = datetime.now() - timedelta(days = 90)).count()
3
>>> from datetime
import datetime, timedelta
>>>
Book.objects.exclude(date_published__gte = datetime.now() - timedelta(days = 90)).count()
17
>>> Book.objects.filter(author__isnull = True).count() 2
>>> Book.objects.filter(title__exact = '').count()
1