Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

190
Vistas
Getting model instance when using QuerySet.values()

Let's say I have two models, one referencing the other:

class Shelf(models.Model):
     pass

class Book(models.Model):
     shelf = models.ForeignKey(Shelf)

I'd like to use values() on a QuerySet of Book instances:

In [1]: Book.objects.create(shelf=Shelf.objects.create())
Out[1]: <Book: Book object>

In [2]: Book.objects.values()
Out[2]: [{'id': 1, 'shelf_id': 1}]

The problem is that the returned dictionaries contain just the primary keys of the related Shelf instances instead of the instances themselves. Is there a way to get the actual instances in a single query? E.g.:

In [2]: Book.objects.values()
Out[2]: [{'id': 1, 'shelf': <Shelf: Shelf object>}]

The reason I'm using values() is so that I can merge two QuerySets for different models which I want to sort and render into a single table in a view.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

According to the docs:

If you have a field called foo that is a ForeignKey, the default values() call will return a dictionary key called foo_id, since this is the name of the hidden model attribute that stores the actual value (the foo attribute refers to the related model).

I don't think it is possible with the default values() implementation. You can create a custom manager and override the values() method to create a multi-level dictionary for each ForeignKey of the model.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda