Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Access ForeignKey value without hitting database

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.

like image 853
Jesse Avatar asked Nov 01 '10 23:11

Jesse


1 Answers

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
like image 91
Dmitry Shevchenko Avatar answered Oct 20 '22 18:10

Dmitry Shevchenko