I am trying to get a list of the content of one attribute from all objects in a model.
For now, I am doing this:
titles_list = []
for item in A.objects.all():
titles_list.append(item.title)
print titles_list
Is there a more interesting solution based on a memory / time economy to do it?
first, which takes a query set and returns the first element, or None if the query set was empty. Instead of writing this: try: object = MyModel.objects.get(key=value) except model.DoesNotExist: object = None.
The simplest way you can get the list of objects of an attribute is to first get a query-set of that attribute alone using values_list then converting the django query-set to a python set using set() and finally to a list using list() .
A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.
pk is short for primary key, which is a unique identifier for each record in a database. Every Django model has a field which serves as its primary key, and whatever other name it has, it can also be referred to as "pk".
The same can be implemented in one line using values_list() with flat=True
:
print A.objects.values_list('title', flat=True)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With