Django - 无需查询数据库访问ForeignKey值
我有一个这样的 Django 模型:
class Profile_Tag(models.Model):
profile = models.ForeignKey(Profile)
tag = models.ForeignKey(Tag)
还有一个这样的视图:
pts = Profile_Tag.objects.all()
for pt in pts:
print pt.profile.id
有没有办法在不每次都访问数据库的情况下获取 profile 的外键?我不想查询 profile 表。我只想从 Profile_Tag 表中获取 ID。
1 个回答
20
你可以这样做:
pt_ids = Profile_Tag.objects.values_list('profile', flat=True)
这样会给你返回一个ID的列表。如果你想要模型实例,还有另外一种方法:
pts = Profile_Tag.objects.all()
for pt in pts:
print pt.profile_id