我正在尝试使用 related_name 进行查询。我需要列出租户及其域。但我收到此错误:
“TenantManager”对象没有属性“domains”
我做错了什么?
模型.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)
序列化器.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()
要返回所有域,但您正在尝试在租户的视图集中使用该查询集。如果它是您真正想要的域对象,请将查询集更改为 Domain.objects.all()