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

时间:2021-10-07 19:18:41

I have a Resident and can not seem to get the set of SSA's the resident belongs to. I've tried res.ssa_set.all() .ssas_set.all() and .ssa_resident_set.all(). Can't seem to manage it. What's the syntax for a reverse m2m lookup through another table?

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

EDIT: I'm getting an 'QuerySet as no attribute' error. Erm?

编辑:我得到一个'QuerySet as no attribute'错误。呃?

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 个解决方案

#1


I was trying to evaluate a query set object, not the object itself. Executing a get on the query set and then a lookup of the relation set worked fine. I'm changing to community wiki and leaving this here just incase someone else is as stupid as I was.

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

A working example:

一个工作的例子:

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

#1


I was trying to evaluate a query set object, not the object itself. Executing a get on the query set and then a lookup of the relation set worked fine. I'm changing to community wiki and leaving this here just incase someone else is as stupid as I was.

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

A working example:

一个工作的例子:

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