外键的 Django 反向查找不起作用

Django Reverse Lookups of Foreign Keys is not working

Info 我在 django 中使用抽象模型,每件事都工作正常而不是查询集我正在尝试查询 Domain与客户端模型有关。但我不明白为什么 外键反向查找 不起作用?

TenantMixin && DomainMixin

class TenantMixin(models.Model):
    schema_name = models.CharField(max_length=63, unique=True, db_index=True)

    class Meta:
        abstract = True

class DomainMixin(models.Model):
    domain = models.CharField(max_length=253, unique=True, db_index=True)
    tenant = models.ForeignKey(settings.TENANT_MODEL, db_index=True, related_name='domains', on_delete=models.CASCADE)

    class Meta:
        abstract = True

客户端

class Client(TenantMixin):
    name = models.CharField(max_length=100)


class Domain(DomainMixin):
    pass

查询集

tenant = Client.objects.all()
    for t in tenant:
        for i in t.domain_set.all():
            print(i)

您将 related_name=… parameter [Django-doc] 设置为 'domains',因此您可以通过以下方式进行反向查找:

tenant = Client.objects.all()
for t in tenant:
    for i in t.<strong>domains</strong>.all():
        print(i)

Note: There is no need to specify db_index=True [Django-doc] for a ForeignKey [Django-doc]. As the documentation specifies: A database index is automatically created on the ForeignKey..