模板中的ManyToMany关系(反向查找)

时间:2017-07-28 14:38:35

标签: python django django-models django-templates django-views

我正在尝试构建自己的客户端数据库,而我却没有让反向查找工作:

models.py

class PersonQuerySet(models.QuerySet):
    def employees(self):
        return self.filter(role='E')

class PersonManager(models.Manager):
    def get_queryset(self):
        return PersonQuerySet(self.model, using=self._db)
    def employees(self):
        return self.get_queryset().employees()

class Person(models.Model):
    people = PersonManager()
    role = models.CharField(max_length=1,
    choices = (('C', _('Client')),('E', _('Employee'))))

class Organization(models.Model):
    employees = models.ManyToManyField(
        Employee,
        limit_choices_to=Q(role='E'),
        related_name='organization_employees',
        related_query_name='organization_employee',)

views.py

class PersonDetail(DetailView):
    model = Person
    template_name = 'clients/person_detail.html'

Organization-Class通过ManyToMany关系与几个员工(Person-Class)相关联。每个员工的DetailView(模板“person_detail.html”)现在可以显示每个员工所属的组织,我想像person.organization.name

这样的东西。

我已尝试过这个以及许多其他解决方案,但它到目前为止从未奏效过,我只是不明白为什么我被卡住了。

<ul>
{% for organization in people.organization_set.all %}
    {{ organization.name }}
{% endfor %}
</ul>

非常感谢任何帮助:)

2 个答案:

答案 0 :(得分:0)

我认为你不能从QuerySet中调用许多反向查找,只能调用模型的一个实例。你可以改用它:

<ul>
{% for person in people %}
    {% for organization in person.organization_set.all %}
        {{ organization.name }}
    {% endfor %}
{% endfor %}
</ul>

您还可以向PeopleQuerySet课程添加方法以添加此功能。

class PersonQuerySet(models.QuerySet):
    def organization_set(self):
        return Organization.objects.filter(pk__in=self.values_list('organization', flat=True))

答案 1 :(得分:0)

如果我向我的Person(models.Model)类添加一个def并执行自定义sql,我找到了一个不同的解决方案。

models.py

class Person(models.Model):
     def get_organization(self):
        with connection.cursor() as cursor:
            cursor.execute('SELECT organization_id FROM clients_organization_employees WHERE employee_id = %s', [self.id])
            organization_id = cursor.fetchone()
            cursor.execute('SELECT name FROM clients_organization WHERE id = %s', [organization_id[0]])
            organization_name = cursor.fetchone()

        for x in organization_name:
            return x

在模板中,我现在可以调用

{{ person.get_organization }}

我总能找到合适的组织,每个员工都属于这个组织。