Django:related_name 问题

Django: related_name issue

我正在尝试使用 related_name 进行查询。我需要列出租户及其域。但我收到此错误:

'TenantManager' object has no attribute 'domains'

我做错了什么?

models.py

class Tenant(TenantMixin):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=100)
    created_on = models.DateField(auto_now_add=True)

    objects = TenantManager()

    auto_create_schema = True
    auto_drop_schema = True


class Domain(DomainMixin):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    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)

managers.py

class TenantManager(models.Manager):

    def list_all(self):        
        return self.domains.all()    

viewsets.py

class TenantViewSets(viewsets.GenericViewSet):

    authentication_classes = (JWTAuthentication,)
    permission_classes = [IsAuthenticated, IsAdminUser, IsSuperUser]

    def list(self, request):      
        queryset = Tenant.objects.list_all()
        serializer = Tenant.Serializer(queryset, many=True)
        return Response(serializer.data) 

serializers.py

class DomainSerializer(serializers.ModelSerializer): 
    tenant = serializers.RelatedField(read_only=True)

    class Meta:
        model = Domain
        fields = (
            "id",
            "domain",
            "tenant",
        )


class TenantSerializer(serializers.ModelSerializer): 
    domain = DomainSerializer(read_only=True)

    class Meta:
        model = Tenant
        fields = (
            "id",
            "name",
            "schema_name",
            "created_on",
            "domain",
        )

您不能在这样的管理器方法上使用 related_name。在管理器上,您可以执行所有常用的 ORM 查询,例如 self.filter()self.get(id=1).

查看您的代码,如果 list_all() 用于 return 所有域,但您正在尝试在针对租户的视图集中使用该查询集。如果它是您真正想要的 doamin 对象,请将查询集更改为 Domain.objects.all()