[Django]-Getting Values of QuerySet in Django

18👍

course_qs = <whatever query gave you the queryset>
for course in course_qs:
    print(course['course_code'])
👤unixia

17👍

Use this

someTable.objects.all()[0]['course_code']

or

someTable.objects.values_list('course_code', flat = True)

10👍

courses = <your query set>
print(courses[0]['course_code'])

4👍

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
👤Ken

3👍

What worked for me:

course_qs = <whatever query gave you the queryset>  
list_of_course = list(course_qs)

When QuerySets are evaluated

  1. The first time you iterate over them
  2. When you slice them, for instance, Post.objects.all()[:3]
  3. When you pickle or cache them
  4. When you call repr() or len() on them
  5. When you explicitly call list() on them
  6. When you test them in a statement, such as bool(), or , and, or if
👤omer

2👍

Okay this is what i did.

1:

items = ItemParent.objects.filter(item_type__contains="something")
# <QuerySet [<Item: iron>]>

2:

items.values()
# <QuerySet [{'id': 5, 'item_parent_id': 8, 'item_type': 'iron', 'item_article_no': '12336'}]>

3:

items.values()["id"]
# 5

When QuerySets is multiple sets:

# <QuerySet [{'id': 5, 'item_parent_id': 8, 'item_type': 'iron', 'item_article_no': '12336'},
#            {'id': 6, 'item_parent_id': 9, 'item_type': 'rust', 'item_article_no': '12338'}]>

item_id_one = items.values()[0]["id"]
item_id_two = items.values()[1]["id"]
# etc..

Or in my case:

for f in items.values()
    item_id = f["id"]

1👍

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

1👍

This returns a Query Set: Django 4.0

result = User.objects.filter(Q(ip__icontains='count')) #<QuerySet [<User: count>]>

This returns the value of count:

result.values('count').get()['count']

However this is crazy compilcated?! There must and should be a simpler solution…

Model:

class User(django.Model):
     count = models.PositiveIntegerField(default=1)

0👍

You can use this:

>>> course_code = str(table_name.objects.all()[0])
>>> course_code
'11'

Leave a comment