Home > front end >  How to Update Django Model Relationship only with Foreign Key Value
How to Update Django Model Relationship only with Foreign Key Value

Time:05-01

I'm looking for a way to update a relationship on a model in Django by only passing the foreign key value and not the model being referenced in the relationship.

I understand that Django wants me to do this

publisher = Publisher.objects.get(id=2)
book = Book.objects.get(id=1)
book.update(publisher=publisher)

But I'm looking to just update the publisher using the publishers PK so something more along the lines of this.

book = Book.objects.get(id=1)
book.update(publisher=2)

I have a significant amount of data that needs to get updated and I don't necessarily have a reference to what the model is for each field that needs to get updated on the "Book".

CodePudding user response:

You can use .filter(…) [Django-doc] here and work with publisher_id:

Book.objects.filter(id=1).update(publisher_id=2)

This will prevent first fetching the Book object with a different query, so normally this will run with a single query to the database.

  • Related