Thanks for your reply, Daniel.  I didn't give my example specifically
enough.  In my particular case I actually have a handle to the Person
and actually don't need all the join dates for all the people in that
group.  I just need that person's join date.

I can see that it is easy to get all membership info for a given
group, but I'm guessing that my original solution is the appropriate
solution for getting the join date for just a single person?

Margie

On Feb 16, 2:05 am, Daniel Roseman <dan...@roseman.org.uk> wrote:
> On Wednesday, February 16, 2011 12:36:49 AM UTC, Margie Roginski wrote:
>
> > Say I am using an intermediary model like that in the doc:
>
> > class Person(models.Model):
> >     name = models.CharField(max_length=128)
>
> > class Group(models.Model):
> >     name = models.CharField(max_length=128)
> >     members = models.ManyToManyField(Person, through='Membership')
>
> > class Membership(models.Model):
> >     person = models.ForeignKey(Person)
> >     group = models.ForeignKey(Group)
> >     date_joined = models.DateField()
>
> > For a given group, say I want to go through the persons in the group
> > and print the date each joined the group.
>
> > beatles = Group.objects.get(name="beatles")
> > for person in group.members.all():
> >    # get join date for person
>
> > What's the best way to do this?  It seems to me that I have to add a
> > related_name to the person field of Membership like this:
>
> >     person = models.ForeignKey(Person, related_name="memberships")
>
> > and then traverse backward from the person back to the membership,
> > filtering to find the correct membership based on the group name.  Can
> > someone tell me if there is a better way?  So I'm thinking I have to
> > do this:
>
> > beatles = Group.objects.get(name="beatles")
> > for person in group.members.all():
> >   joinDate = person.memberships.filter(group_name="beatles")
> > [0].date_joined
>
> > Thanks for any pointers,
>
> > Margie
>
> It's easier than that. You can get all memberships for a group in one go:
>
>     memberships =
> Membership.objects.filter(group__name="beatles").select_related()
>     for m in memberships:
>         print m.person.name, m.date_joined
>
> --
> DR.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to