КАК ИЗМЕНИТЬ ЗНАЧЕНИЕ ВНЕШНЕГО КЛЮЧА И СОХРАНИТЬ В БД ЧЕРЕЗ ФУНКЦИЮ (РЕШЕНО)
Я ХОТЕЛ ИЗМЕНИТЬ ЗНАЧЕНИЕ ВНЕШНЕГО КЛЮЧА С ПОМОЩЬЮ ФУНКЦИИ. ВОТ МОЕ РЕШЕНИЕ. Я ДУМАЮ, ЧТО ЭТО БУДЕТ ПОЛЕЗНО ДЛЯ КОГО-ТО В ОДИН ПРЕКРАСНЫЙ ДЕНЬ. ПОСМОТРИТЕ МОЙ ОТВЕТ НИЖЕ
def foo(request, pk):
foo = Model.object.get(pk=pk)
if foo:
foo.foreignkey_id = id_number # you have to write "_id" to notify that you want the foreign key id and the id_number must be the exact id number of your foreign key
foo .save() # save it in the database
Вы можете уменьшить количество запросов, используя .update(…)
[Django-doc], и таким образом работать с:
def my_view(request, pk):
Model.objects.filter(pk=pk).update(foreignkey_id=id_number)
# …
This will reduce the amount of bandwidth, and also only update that specific field. If you defined a ForeignKey
with the name foreignkey
, foreignkey_id
contains the value of the to_field=…
[Django-doc]. This is by default the primary key field of the target model, but thus can be another unique field if that is specified.