简体   繁体   中英

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:

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.

However, the SELECT query isn't really necessary as it will be the mypk that is inserted into the foreign key field. Is there a way to get Django to just insert the primary key without doing a 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.

Simply set myForeignModel_id to the FK value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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