Search code examples
djangodjango-modelsmany-to-manymanytomanyfield

Search a Many to Many Relationship


Given a Contributor, I'm trying to find the Registrations the Contributor belongs to. I can't figure out how to traverse the M2M- I need to know which Registrations contain the Contributor in their 'conrtibutor' field...?

class Registration(TimeStampedModel):
    dataset = models.ForeignKey('Dataset', related_name='registration')
    contributor = models.ManyToManyField('Contributor', related_name='registrations')   # many contributors may be involved with this registration

    def __unicode__(self):
        return self.dataset.dataset_name

class Contributor(models.Model):
    name = models.CharField(max_length=256, blank=False)
    email = models.EmailField(blank=False)

    def which_registration(self):
            registrations = Registration.objects.filter(contributor_contains=self)
            datasets = []
            for x in registrations:
                datasets.append(x.dataset)
            return datasets

Solution

  • I think you just need this:

    # assuming you have a contributor
    Registration.objects.filter(contributor=your_contributor_object)