249👍
✅
You can do this using values_list
method.
blogs = Blog.objects.filter(author=author).values_list('id', flat=True)
See more at the Django queryset documentation.
78👍
Blog.objects.filter(author=author).values_list('id', flat=True)
values_list()
gives a list of rows, each row a tuple of all of the fields you specify as arguments, in order. If you only pass a single field in as an argument, you can also specify flat=True
to get a plain list instead of a list of tuples.
- [Django]-Django set field value after a form is initialized
- [Django]-Warning: Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'
- [Django]-Trying to migrate in Django 1.9 — strange SQL error "django.db.utils.OperationalError: near ")": syntax error"
12👍
Blog.objects.filter(author=author).values_list('pk', flat=True)
Put pk
instead id
, just for best practices.
- [Django]-What does "'tests' module incorrectly imported" mean?
- [Django]-How to rename items in values() in Django?
- [Django]-How to test auto_now_add in django
6👍
values_list
it returns tuples when iterated over. Each tuple contains the value from the respective field or expression passed into the values_list().
author = Blog.objects.filter(author=author)
ids = author.values_list('pk', flat=True)
# list method get ids without parse the returning queryset
print(list(ids))
- [Django]-What is "load url from future" in Django
- [Django]-Having Django serve downloadable files
- [Django]-Modulus % in Django template
Source:stackexchange.com