to obtain the foreign key value without fetching the entire object?


say I have these models:

class Parent(models.Model):
    slug = models.SlugField()class Child(models.Model):
    slug = models.SlugField()
    parent = models.ForeignKey('Parent')

I want to create a dict:

{ : x.slug for x in Child.objects.all()}

this code generates a separate database query for each iteration. just to get the Parent object, just to get its primary key. which is right there in the Child object to begin with! I do not need anything from the parent, just its primary key. How do I get the value of the underlying foreign key?

(yes, I know that I can use select_related() to get rid of these extra queries, but my question is not about that.)


This should work

{x.parent_id : x.slug for x in Child.objects.all()}