[Answer]-Django: How to avoid reassigning ForeignKey on every save?

1đź‘Ť

“A has a foreignkey to B. B has a OneToOneField to A.” I don’t think this is the way to set up your relationships. You can just set B as a ForeignKey of A and then you can access A from B using B.a_set.all().

To paraphrase from here, with the following model definitions, Book is one-to-many (ForeignKey) with Publisher and many-to-many with Author. (The ~~~~ just means other stuff not related to the relationships between the models)

class Publisher(~~~~):
    ~~~~

class Author(~~~~):
    ~~~~

class Book(~~~~):
    publisher = models.ForeignKey(Publisher)
    authors = models.ManyToManyField(Author)

Then you can access publisher and author from a given book like so:

b = Book.objects.get(id=50)
publisher1 = b.publisher # publisher object for a given book
author_set = b.authors.all() # query set of authors for a given book

and you can do the reverse relationship (which isn’t explicitly defined in the models above).

p = Publisher.objects.get(name='Apress Publishing')
p.book_set.all() # query set of books for a given publisher
publisher1.book_set.all() # set of books for the publisher from above.
a = Author.objects.get(name="JK Rowling")
a.book_set.all() # query set of books for a given author

Any time you update an object field you need to call save() to save it in the database, but you shouldn’t need to reassign ForeignKey or any other field before doing so. If that wasn’t working for you, maybe it was because of the funky relationship between the models. I’m not 100% sure, but I think the only time an object gets a (new) primary key is the first time it’s saved to the database, and then that’s its first pk.

👤Xephryous

Leave a comment