Member-only story

Django ORM: values and values_list

Brent Fischer
4 min readNov 8, 2024

In Django, the ORM (Object-Relational Mapping) allows working with databases in a Pythonic way, without the need to write SQL directly. Two of the most useful methods for retrieving data in a specific structure are values() and values_list(). These methods help selectively fetch specific fields from a database query and return the query results in the form of a dictionary or a list.

This tutorial explains the basics of the values and values_list methods and demonstrates how to use them in Django.

Setting Up the Example

Use a simple Django model as the basis for the examples. The Book model here represents a book with the fields title, author, and publication year.

# models.py
from django.db import models

class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
year_published = models.IntegerField()
def __str__(self):
return self.title

With this model in your Django app, we can use the values and values_list methods to access specific data.

values(): Results as Dictionary

The values() method returns fields as dictionary-like objects. This is useful if you want specific fields and their names as key-value pairs.

--

--

Brent Fischer
Brent Fischer

Written by Brent Fischer

Python Developer, Python Trainer, Geek, RPGs, Pizza, Traveller. Loves Rust, C, Linux. Drop by at friendlybytes.net

No responses yet