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.