title: Retrieving objects from many-to-many with abstract class in Django
body: <p>My question is similar to <a href="https://stackoverflow.com/questions/933092/generic-many-to-many-relationships">this</a>, but creating junction table is not good in this particular case.</p>
  
  <p>Short snippet of a model:</p>
  
  <pre><code>class Item(models.Model):
      photos = models.ManyToManyField('Photo', blank=True, null=True, related_name='photo_in_%(class)ss')
  
      class Meta:
          abstract = True 
  </code></pre>
  
  <p>Then I have <strong>many</strong> classes like this:</p>
  
  <pre><code>class Article(Item): pass
  class BlogEntry(Item): pass
  class Country(Item): pass
  ...
  </code></pre>
  
  <p>And of course:</p>
  
  <pre><code>class Photo(models.Model):
      pass
  </code></pre>
  
  <p>Having e.g. <code>a = Article()</code> I can easily get photos in article with <code>a.photos.all()</code></p>
  
  <p>The question is: having <code>p = Photo()</code> how to retrieve all objects with this photo?</p>
  
  <p><strong>But:</strong></p>
  
  <p>Generic relation is not an option. Each photo can be in various items' photos simultaneously.</p>
  
  <p>I came up with such a method, though. But it uses eval and <em>eval is evil</em>...</p>
  
  <pre><code>class Photo(models.Model):
      def get_items_with_photo(self):
          items = []
          for cl in [name for name in dir(self) if name.startswith('photo_in')]:
              qset = eval('self.%s.all()' % (cl))
              [items.append(item) for item in qset]
          return items
  </code></pre>
  
  <p>I would appreciate any different (better) solution.</p>