开发者

Django - Access ForeignKey value without hitting database

开发者 https://www.devze.com 2023-01-23 05:44 出处:网络
I have a django model like so: class Profile_Tag(models.Model): profile = models.ForeignKey(Profile) tag = models.ForeignKey(Tag)

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号