title: Django many-to-many relations, and through
body: <p>I want to store which user invited another user to a group... but django is telling me this is ambigous and against the rules (which makes sense). </p>
  
  <blockquote>
    <p>groups.group: Intermediary model
    Group_to_Member has more than one
    foreign key to User, which is
    ambiguous and is not permitted.</p>
  </blockquote>
  
  <p>So how do I do this correctly? Maybe a generic relation? might work but seems a bit convoluted... Here's how I was approaching it (with unrelated bits removed)</p>
  
  <pre><code>from django.contrib.auth.models import User
  
  class UserGroup(models.Model):
      members = models.ManyToManyField(User, through='Group_to_Member')
  
  class UserGroup_to_Member(models.Model):
      group = models.ForeignKey(UserGroup)
      member = models.ForeignKey(User)
  
      invited_by = models.ForeignKey(User, related_name="group_invited_users")
  </code></pre>
  
  <h2>Solution</h2>
  
  <p>Ok so I did a little combination of the answers you guys provided (Thanks!) and things I found on the internet plus my own admittedly meager python-fu:</p>
  
  <pre><code>from django.contrib.auth.models import User
  
  class UserGroup(models.Model):
      # notice there is no member object here
      ... other model data
  
      def add_member(self, **kwargs):
          g2m = UserGroup_to_Member(group = self,  **kwargs)
          g2m.save()
  
      def remove_member(self, member):
          g2m = UserGroup_to_Member.objects.get(group=self, member=member)
          g2m.delete()
  
      # This is not elegant at all, help please? I'm pretty sure it isn't
      # as bad on the database as it looks though.
      def get_members(self):
          g2ms = UserGroup_to_Member.objects.filter(group=self)
          member_ids = [g2m.member.id for g2m in g2ms]
          members = User.objects.none()
          for id in member_ids:
              members = members | User.objects.get(id=id)
          return members
  
  class UserGroup_to_Member(models.Model):
      group = models.ForeignKey(UserGroup)
      member = models.ForeignKey(User)
  
      invited_by = models.ForeignKey(User, related_name="group_invited_users")
  </code></pre>