开发者

Preventing select query on ForeignKey when the primary key is known

开发者 https://www.devze.com 2023-03-09 04:03 出处:网络
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

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 re开发者_运维问答ally 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消