Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

188
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!