搜索多对多关系

Search a Many to Many Relationship

给定一个投稿人,我试图找到投稿人所属的注册。我不知道如何遍历 M2M - 我需要知道哪些注册在其 'conrtibutor' 字段中包含贡献者...?

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

我想你只需要这个:

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

使用related_name进行反向访问。

def which_registration(self):
    #if you dont define related_name you should use
    #return self.registration_set.all()
    return self.registrations.all()