In my models, I have different types of relationships between Event
s and Profile
s. I want to work with the profiles that are an event’s promoters in a templae, so I’ve created a promoters
property.
Right now, the @property
returns a generator:
class ProfileEventRelationship(models.Model):
class RelationshipType(models.TextChoices):
PROMOTER = "P"
OTHERS = "*"
profile = models.ForeignKey(
Profile,
on_delete=models.CASCADE,
related_name="event_relationships",
)
event = models.ForeignKey(
"Event", on_delete=models.CASCADE, related_name="profile_relationships"
)
relationship_type = models.CharField(max_length=1, choices=RelationshipType)
class Event(models.Model):
@property
def promoters(self):
return (
pr.profile
for pr in self.profile_relationships.filter(
relationship_type=ProfileEventRelationship.RelationshipType.PROMOTER
)
)
… but filters like first
don’t work with generators: ‘generator’ object is not subscriptable.
So what’s the right way to do this in Django? Is there a way to wrap a QuerySet
around a generator, that also caches the data, so it’s not expensive to first check whether there are any promoters?
Actually, in this case, I only really expect one or two promoters, so just returning a list
would be fine. But is a more Djangoistic way, that would also work for large numbers of items, say for pagination?
Also, is there a less verbose way to write that promoters
filter, where I don’t have to specify the whole relationship class name?