Django - Access ForeignKey value without hitting database
Asked Answered
S

1

16

I have a django model like so:

class Profile_Tag(models.Model):
    profile = models.ForeignKey(Profile)
    tag = models.ForeignKey(Tag)

and a view like so:

pts = Profile_Tag.objects.all()
for pt in pts:
    print pt.profile.id

is there any way to access the profile foreignKey without hitting the database each time? I don't want to query the profile table. I just want to grab the ids from the Profile_Tag table.

Sexology answered 1/11, 2010 at 23:49 Comment(2)
How do you know it "hits" the database? There is extensive cache management both in the ORM layer as well as the database.Barclay
Well, to anyone else reading this and to answer Lott's question... it does do a DB hit in Django 1.4 (at least). You can turn on the database logging to see all the queries and pt.profile.id results in a query while pt.profile_id does not. It's possible for them to make the call to .id not result in a hit so it's possible this may change in the future (or already is different, I haven't tested newer versions).Friede
S
20

You can do something like this:

pt_ids = Profile_Tag.objects.values_list('profile', flat=True)

This will return you list of IDs. For model instance, there's another way:

pts = Profile_Tag.objects.all()
for pt in pts:
    print pt.profile_id
Sidran answered 2/11, 2010 at 0:0 Comment(1)
excellent. thank you. guess i should have thought to try thatSexology

© 2022 - 2024 — McMap. All rights reserved.