I tried to run this example on my computer but when I restart the python surprisingly the created polls are saved to the database without a visible save statement.
Here is the code:
>>> from polls.models import Poll, Choice
>>> Poll.objects.all()[0].choice_set.create(choice='Not much', votes=0)
<Choice: Not much>
So I wonder by which statements save instructions are implied ? Because if I create it like this, it won’t survive a restart.
>>> c = Choice(choice='Not much3', votes=0)
>>> c.poll_id = 1
I am creating a choice and I am assigning the foreign key poll_id to the first poll. I know this shouldn’t last because I didn’t save. It is the first one that tricks me, I assume if I create it within the associated set it also automatically saves not only gives it’s proper foreign id.
I am also new to python, and semantics seemed just a little bit loose based on my prior experience on this issue. I’d expect first code to just assign the proper foreign id not also save it to the database.
Using the create() method on a QuerySet will automatically save the object, as specified in the documentation.
You can think of it as effectively an SQL INSERT statement.