如何在不加载相应项的情况下读取ForeignKey的主键?
我有 2 个 Django 模型:
class A(models.Model):
uniq_name = models.CharField(max_length=30,primary_key=True)
info1 = models.CharField(max_length=30)
info2 = models.CharField(max_length=30)
class B(models.Model):
a = models.ForeignKey(A)
info3 = models.CharField(max_length=30)
info4 = models.CharField(max_length=30)
如果我这样做:
b = B.objects.get(id = n), it generates one database request.
如果我
print b.a.pk : it generate another request.
这样做 是否可以访问 ba 主键(我只需要此信息,而不是 info1 或 info2)而不生成另一个请求或使用“select_lated()”?
我可以做一个:
print b.__dict__['a_id']
它有效,但在我看来很难看:你有更好的方法吗?
I have 2 Django models :
class A(models.Model):
uniq_name = models.CharField(max_length=30,primary_key=True)
info1 = models.CharField(max_length=30)
info2 = models.CharField(max_length=30)
class B(models.Model):
a = models.ForeignKey(A)
info3 = models.CharField(max_length=30)
info4 = models.CharField(max_length=30)
If I do :
b = B.objects.get(id = n), it generates one database request.
If I do
print b.a.pk : it generate another request.
Is that possible to access b.a primary key (I only need this information, not info1 nor info2) without generating another request nor using 'select_related()' ?
I could do a :
print b.__dict__['a_id']
It works, but it seems to me very ugly : do you have a nicer way ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不需要通过字典:
b.a_id
工作正常。You don't need to go via the dict:
b.a_id
works fine.不。就是这样做的。
No. That's how it's done.
如果你想动态地执行此操作(就像我一样):
If you want to do this dynamically (like I did):