Django:使用整数设置外键?

编程入门 行业动态 更新时间:2024-10-27 10:34:14
本文介绍了Django:使用整数设置外键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有没有办法使用模型的整数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:使用整数设置外键?

本文发布于:2023-10-14 21:36:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1492281.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   Django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!