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.
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.