'Django models | get specific columns

Is there a way to filter and get only specific columns?

For example, get all entries with the column first_name.



Solution 1:[1]

QuerySet.values() or QuerySet.values_list(), e.g.:

Entry.objects.values('first_name')

Solution 2:[2]

If you want a list of only the values, use:

Entry.objects.values_list('first_name', flat=True)

Solution 3:[3]

To only get a column's values from the table but still return an object of that model, use only:

record = Entry.objects.only('first_name')

This will defer all other columns from the model but you can still access them all normally.

record.first_name # already retrieved
record.last_name  # retrieved on call

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MD. Khairul Basar
Solution 2 Daniel Nicolae
Solution 3 Akaisteph7