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开发者_如何学Go profile table. I just want to grab the ids from the Profile_Tag table.
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
精彩评论