Django Model API通过中间表反向查找多对多关系

时间:2009-02-15 04:03:14

标签: python django django-models many-to-many

我有一个居民,似乎无法获得居民所属的SSA集。我试过了res.ssa_set.all() .ssas_set.all().ssa_resident_set.all()。似乎无法管理它。通过另一个表进行反向m2m查找的语法是什么?

编辑:我收到'QuerySet as no attribute'错误。 ERM?

class SSA(models.Model):
    name = models.CharField(max_length=100)
    cost_center = models.IntegerField(max_length=4)
    street_num = models.CharField(max_length=9)
    street_name = models.CharField(max_length=40)
    suburb = models.CharField(max_length=40)
    post_code = models.IntegerField(max_length=4, blank=True, null=True)

    def __unicode__(self):
        return self.name

class Resident(models.Model):
    cris_id = models.CharField(max_length=10, primary_key=True)
    first_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=20)
    ssas = models.ManyToManyField('SSA', through='SSA_Resident', verbose_name="SSAs")

    def __unicode__(self):
        return self._get_full_name()

    def _get_full_name(self):
        return u"%s %s" %(self.first_name, self.last_name)

    full_name = property(_get_full_name)

class SSA_Resident(models.Model):
    id = models.AutoField(primary_key=True)
    resident = models.ForeignKey('Resident')
    ssa = models.ForeignKey('SSA', verbose_name="SSA")
    active = models.BooleanField(default=True)
    def __unicode__(self):
        return u"%s - %s" %(self.resident.full_name, self.ssa.name)

1 个答案:

答案 0 :(得分:1)

我试图评估查询集对象,而不是对象本身。在查询集上执行get,然后查找关系集就可以了。我正在改为社区维基,把它留在这里只是因为别人和我一样愚蠢。

一个工作示例:

resident = Resident.objects.filter(name='Johnny')
resident.ssa_set.all() # fail
resident = resident.get() # will fail if more than one returned by filter
resident.ssa_set.all() # works, since we're operating on an instance, not a queryset