Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The main issue has to do with side effects that are wanted or not. And with variables really being pointers to objects in Python.</p> <p>When you create an object out of a model, it doesn't have a primary key yet as you haven't saved it yet. But, when saving it, should Django have to make sure it updates attributes on the already-existing object? A primary key is logical, but it would also lead you to expect other attributes being updated.</p> <p>An example for that is Django's unicode handling. Whatever charset you give the text you put into a database: Django gives you unicode once you get it out again. But if you create an object (with some non-unicode attribute) and save it, should Django modify that text attribute on your existing object? That already sounds a little bit more dangerous. Which is (probably) why Django doesn't do any on-the-fly updating of objects you ask it to store in the database. </p> <p>Re-loading the object from database gives you a perfect object with everything set, but it also makes your variable point to a different object. So that would not help in your example in case you already gave the Rating a pointer at your "old" Movie object.</p> <p>The <code>Movie.objects.create(title="The Hobbit")</code> mentioned by Hedde is the trick here. It returns a movie object <em>from the database</em>, so it already has an id.</p> <pre><code>the_hobbit = Movie.objects.create(title="The Hobbit") my_rating = Rating(movie=the_hobbit, rating=8.5) # No need to save the_hobbit, btw, it is already saved. my_rating.save() </code></pre> <p>(I had problems with the difference between my objects and objects from the database, too, when my newly created object didn't output unicode. The <a href="http://reinout.vanrees.org/weblog/2011/11/18/django_unicodedecodeerror.html">explanation</a> I put on my weblog is the same as above, but worded a bit differently.)</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload