简体   繁体   English

当主键已知时,防止对 ForeignKey 的 select 查询

[英]Preventing select query on ForeignKey when the primary key is known

to insert a row to a table that has a one-to-one relationship, you would do this in Django:要向具有一对一关系的表中插入一行,您可以在 Django 中执行此操作:

mypk=2   # Comes from the POST request
model=MyModel(myField="Hello", myForeignModel=ForeignModel.objects.get(pk=mypk))
model.save()

This will cause a SELECT query followed by an INSERT query.这将导致 SELECT 查询,然后是 INSERT 查询。

However, the SELECT query isn't really necessary as it will be the mypk that is inserted into the foreign key field.但是,SELECT 查询并不是真正需要的,因为它将mypk插入到外键字段中。 Is there a way to get Django to just insert the primary key without doing a SELECT?有没有办法让 Django 只插入主键而不执行 SELECT?

Secondly, are there concurrency issues here (in the event that the primary key would change before the user submits the request).其次,这里是否存在并发问题(如果主键在用户提交请求之前发生更改)。 If so, how are these dealt with?如果有,这些是如何处理的?

From the docs :文档

Behind the scenes, Django appends "_id" to the field name to create its database column name.在幕后,Django 将"_id"附加到字段名称以创建其数据库列名称。

Simply set myForeignModel_id to the FK value.只需将myForeignModel_id设置为 FK 值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM