Home > Software engineering >  How to change a foreign key using a Python function
How to change a foreign key using a Python function

Time:06-18

I wanted to change the foreign key value using a function. Here is my solution which I think will be helpful for someone one day. My answer is below.

CodePudding user response:

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

CodePudding user response:

You can reduce the amount of querying by making use of .update(…) [Django-doc], and thus work with:

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.

  • Related