Home > Net >  HOW TO CHANGE THE FOREIGN KEY VALUE AND SAVE IN DB TROUGHT A FUNCTION (RESOLVED)
HOW TO CHANGE THE FOREIGN KEY VALUE AND SAVE IN DB TROUGHT A FUNCTION (RESOLVED)

Time:06-18

I WANTED TO CHANGE THE FOREIGN KEY VALUE TROUGHT A FUNCTION. SO HERE IS MY SOLUTION. I THNINK THIS WILL BE HELPFUL FOR SOMEONE ONE DAY. LOOK MY ANSWER 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