Django:使用整数设置外键? [英] Django: Set foreign key using integer?
问题描述
有没有办法使用模型的整数id设置外键关系?这将是为了优化目的。
例如,假设我有一个Employee模型:
$ $
first_name = models.CharField(max_length = 100)
last_name = models.CharField(max_length = 100)
type = models。 ForeignKey('EmployeeType')
和
EmployeeType(models.Model):
type = models.CharField(max_length = 100)
我希望拥有无限员工类型的灵活性,但在部署的应用程序中可能只有一种类型,所以我想知道是否有办法硬编码,并设置这种关系。这样我可以避免使用db调用来获取EmployeeType对象。
是的:
employee = Employee(first_name =Name,last_name =Name)
employee.type_id = 4
employee.save()
ForeignKey
fields将其值存储在属性中 _id
在最后,您可以直接访问以避免访问数据库。
_id
版本的 ForeignKey
是Django特别有用的一个方面,每个人都应该在适当的时候知道和使用。 / p>
警告:
@RuneKaagaard指出,即使在调用
不准确。使用它当然会失败上述优化的目的,但我更喜欢意外的额外查询不正确。所以要小心,只有当你完成了实例的工作(例如 employee.save()
(它保留其旧值)后,最近的Django版本中.type employee
)才可以使用。
Is there a way to set foreign key relationship using the integer id of a model? This would be for optimization purposes.
For example, suppose I have an Employee model:
class Employee(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
type = models.ForeignKey('EmployeeType')
and
EmployeeType(models.Model):
type = models.CharField(max_length=100)
I want the flexibility of having unlimited employee types, but in the deployed application there will likely be only a single type so I'm wondering if there is a way to hardcode the id and set the relationship this way. This way I can avoid a db call to get the EmployeeType object first.
Yep:
employee = Employee(first_name="Name", last_name="Name")
employee.type_id = 4
employee.save()
ForeignKey
fields store their value in an attribute with _id
at the end, which you can access directly to avoid visiting the database.
The _id
version of a ForeignKey
is a particularly useful aspect of Django, one that everyone should know and use from time to time when appropriate.
caveat:
@RuneKaagaard points out that employee.type
is not accurate afterwards in recent Django versions, even after calling employee.save()
(it holds its old value). Using it would of course defeat the purpose of the above optimisation, but I would prefer an accidental extra query to being incorrect. So be careful, only use this when you are finished working on your instance (eg employee
).
这篇关于Django:使用整数设置外键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!