Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango: how to add a non-database object to query results
    text
    copied!<p>Let's consider a situation where I have a bunch of people who own some shirts:</p> <pre><code>class Person(models.Model): name = models.CharField() class Shirt(models.Model): description = models.CharField() owner = models.ForeignKey(Person) </code></pre> <p>I take portrait photos of them in one of their shirts:</p> <pre><code>class Photo(models.Model): person = models.ForeignKey(Person) shirt = models.ForeignKey(Shirt) </code></pre> <p>In templates I use stuff like</p> <pre><code>{{ the_photo.shirt.description }} </code></pre> <p>and</p> <pre><code>{% for shirt in the_person.shirt_set.all %} {{ shirt.description }} {% endfor %} </code></pre> <p>I also have forms to let me pick a shirt for a photo from the model's inventory.</p> <p>Now, a twist! I can also take a photo of them without a shirt! So I want <code>the_person.shirt_set</code> to contain also a <code>description='topless'</code> entry in additional to any shirts they might own. I'd rather not store an additional <code>'topless'</code> shirt for each person and wouldn't like to have to modify each form and list to add this option.</p> <p>I had an idea of creating a <code>Topless</code> class:</p> <pre><code>class Topless(Shirt): def __init__(self, *args, **kwargs): super(Topless, self).__init__(*args, **kwargs) self.description = 'Topless' </code></pre> <p>and adding it to lists:</p> <pre><code>class Person(models.Model): name = models.CharField() def shirts(self): l = list(Shirt.objects.filter(owner=self)) l.insert(0, Topless()) return l </code></pre> <p>(and switching from <code>the_person.shirt_set</code> to <code>the_person.shirts</code> in templates of course), but it's getting ugly with <code>the_photo.shirt</code> since the id is None (or 0) and it looks like it will require a bunch of ugly hacks to accommodate for that.</p> <p>But maybe I'm doing it wrong? Any ideas? What's the most elegant and pythonic way to do it?</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