Reputation: 614
Here is a models example.
class Person(models.Model):
name = models.CharField(max_length=128)
def __unicode__(self):
return self.name
class Group(models.Model):
name = models.CharField(max_length=128)
def __unicode__(self):
return self.name
class Membership(models.Model):
person = models.ForeignKey(Person)
group = models.ForeignKey(Group)
I want to get all Person objects, and for each one adding a column 'is_member' that values True if the person is member at least of one group.
I try with annotate and count, but I'm a bit confused... Thank you.
Upvotes: 1
Views: 136
Reputation: 2569
Try this :
Person.objects.annotate(
is_member=Case(
When(membership=True, then=True), default=False, output_field=BooleanField()
)
).distinct('id')
if you want learn more about this, conditional-expressions can help u.
Upvotes: 1
Reputation: 19806
The following should work for you:
persons = []
for p in Person.objects.all():
if p.membership_set.all():
p.is_member = True
else:
p.is_member = False
persons.append(p)
Upvotes: 0