Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Update Django Model Relationship only with Foreign Key Value

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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".

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading