python - Django Integrity error _id may not be null, ForeignKey id assignment -


i'm having issues understanding way django (v1.6.5) assigns id different objects when saving. taking minimal example:

#models.py  class book(models.model):     title = models.charfield(max_length=10)  class page(models.model):     number = models.smallintegerfield()     book   = models.foreignkey(book) 

the following view throws "integrityerror,book_id may not null" when saving my_page, tend book_id exist since save() has been called book @ stage.

#view.py  my_book = book(title="my book")  #solution1 : having my_book.save() here  my_page = page(number = 1, book = my_book) my_book.save() print("book id",my_page.book.id) #book.id exist @ point!  #solution2: my_page.book = my_book  my_page.save()   #throws integrityerror exception 

there easy solutions make code above work know wrong first approach. missing or glitch/limitation in way django handles foreignkeys?

i see point, current behavior seems more explicit. my_book python object, , of attributes (including id) can change. seems safer assume user wants value exists @ instantiation time.

for example, django idiom copying database row involves reusing same object represent more 1 model instance. in case might like:

my_book = book(title="my book") my_page = page(number=1, book=my_book) my_book.save()  my_book.id = none my_book.save()  # copy book new row new id  my_page.save() 

so book should my_page point to? think developers right require explicit here. solution the associated ticket more direct in valueerror when trying instantiate my_page if my_book hasn't yet been saved.


Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -