Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I force django to use the lowest model instance?
    text
    copied!<p>Suppose I have my models set up like this:</p> <pre><code>class B(Model): ... def __str__(self): return "B" class C(B): ... def __str__(self): return "C" class A(Model): b = ForeignKey(B) def __str__(self): print "A: %s"%(self.b) a = A(b=C(...)) a.save() print str(a) # Prints "A: B" </code></pre> <p>Maybe I'm a bit confused how django inheritance works. My intention is to have the program print <code>"A: C"</code> at runtime (since <code>A.b</code> is an instance of model <code>C</code>)</p> <p>I think I <em>might</em> be asking about <a href="https://docs.djangoproject.com/en/dev/topics/db/models/#multi-table-inheritance" rel="nofollow">multi-table inheritance</a>. But that's only if you know what instance of a subclass you want.</p> <p>As another example of how I'm confused, I'd like to borrow the example from the docs:</p> <pre><code># Assume Restaurant, Park, and Museum inherit Place bills = Restaurant.objects.create(name="Bill's Pub", burger="Bill's Burger") city_prk = Park.objects.create(name='City Park', num_trails=5) nose = Museum.objects.create(name='Nose Museum', est=1940) places = Places.objects.all() </code></pre> <p>I'll definitely get a list of 3 objects (of type <code>Place</code>) but I have no way of differentiating the types of places. For example, if I want to print out the str value of each place...</p> <pre><code>for place in places: print str(place) </code></pre> <p>...python will just execute <code>Place.__str__()</code> and not <code>Restaurant.__str__()</code> (for the restaurant) or <code>Park.__str__()</code> (for the park). This doesn't seem to happen with "normal" python. Python should normally automatically find the lowest-inherited class and execute the overridden function from that (if B overrides a method from A, B's method will be executed).</p> <p>Are my assumptions correct? Sorry for the long question (and sorry if it's not clear). I'm not exactly sure how to ask what I'm wondering.</p>
 

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