2

My question is similar to this, but creating junction table is not good in this particular case.

Short snippet of a model:

class Item(models.Model):
    photos = models.ManyToManyField('Photo', blank=True, null=True, related_name='photo_in_%(class)ss')

    class Meta:
        abstract = True 

Then I have many classes like this:

class Article(Item): pass
class BlogEntry(Item): pass
class Country(Item): pass
...

And of course:

class Photo(models.Model):
    pass

Having e.g. a = Article() I can easily get photos in article with a.photos.all()

The question is: having p = Photo() how to retrieve all objects with this photo?

But:

Generic relation is not an option. Each photo can be in various items' photos simultaneously.

I came up with such a method, though. But it uses eval and eval is evil...

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

I would appreciate any different (better) solution.

Community
  • 1
  • 1
laszchamachla
  • 763
  • 9
  • 21

1 Answers1

0

Instead of:

qset = eval('self.%s.all()' % (cl))

do:

photo_attr = getattr(self, cl)
qset = photo_attr.all()
Etienne
  • 12,440
  • 5
  • 44
  • 50
  • Thanks - works great! I assume that there is no Django-like approach to do such a thing? – laszchamachla Oct 05 '11 at 06:23
  • Why have a Django-like approach when the Python approach already work? No need to reinvent the wheel. If it work great, you should accept the answer! – Etienne Oct 05 '11 at 13:32
  • Just because not every Python approach works well while modelling and dealing with Django's ORM. I know I should accept your answer - but what's the hurry ;)? – laszchamachla Oct 05 '11 at 23:11