Given the Model:
class Profile(models.Model):
user = models.ForeignKey(User, unique=True)
class Thingie(models.Model):
children = models.ManyToManyField('self', blank=True, symmetrical=False)
class Relation(models.Model):
profile = models.ForeignKey(Profile)
thingie = models.ForeignKey(Thingie)
How would one return a QuerySet containing all Profile instances related to a given Thingie? That is, every Profile that has a foreign key pointing to it from a Relation and to the given thingie.
I know all about select_related(), and how I could use it to do this by iterating but i find iterating irritating (badoop bah!). Also, values_list() has been looked at, but it doesn’t quite do the right thing.
Please help! Thanks!
Do you definitely need it to be a queryset? If you only need it to be an iterable, a simple expression for your purposes is:
I’m not sure if a list comprehension counts as irritating iterating, but to me this is a perfectly intuitive, pythonic approach. Of course if you need it to be a queryset, you’re going to do something messier with two queries, eg:
See the “in” documentation for more. I prefer the first approach, if you don’t need a queryset. Oh and if you only want distinct profiles you can just take
set(profiles)in the first approach or use thedistinct()queryset method in the second approach.