Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Get the first attribute from all objects in a Model

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?

like image 245
Erwan Avatar asked Apr 02 '14 13:04

Erwan


People also ask

What is first () in Django?

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.

How do you get or view all the items in a model in Django?

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() .

What is a QuerySet in Django?

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.

What is PK in Django?

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".


1 Answers

The same can be implemented in one line using values_list() with flat=True:

print A.objects.values_list('title', flat=True)
like image 143
alecxe Avatar answered Sep 30 '22 12:09

alecxe