Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

189
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda