You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django迁移未使用配置的数据库连接问题排查

解决方案

1. 明确指定SupabaseUser模型的完整表名(带schema)

修改auth/models.py中的db_table,加上auth schema前缀,让Django生成外键约束时能正确指向Supabase托管的auth.users表:

# auth/models.py
class SupabaseUser(models.Model):
    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        verbose_name="User ID",
        help_text="Supabase managed user id",
        editable=False,
    )

    class Meta:
        managed = False
        db_table = "auth.users"  # 新增auth schema前缀

2. 修正数据库路由的迁移权限逻辑

因为SupabaseUser是Supabase托管的表(managed=False),不需要Django执行迁移操作,调整路由的allow_migrate方法,避免无效的迁移尝试:

from django.db.models import Model
from django.db.models.options import Options


class ModelRouter:
    @staticmethod
    def db_for_read(model: Model, **kwargs):
        return ModelRouter._get_db_schema(model._meta)

    @staticmethod
    def db_for_write(model: Model, **kwargs):
        return ModelRouter._get_db_schema(model._meta)

    @staticmethod
    def allow_migrate(db, app_label, model: Model=None, model_name=None, **kwargs):
        # 禁止auth app的模型执行任何迁移(表由Supabase维护)
        if app_label == "auth":
            return False
        # 仅允许default数据库处理其他app的迁移
        return db == "default"

    @staticmethod
    def _get_db_schema(options: Options) -> str:
        if options.app_label == "auth":
            return "supabase_auth"
        return "default"

3. 重新执行迁移操作

先删除myapp下之前生成的错误迁移文件(比如0013_mymodel_user.py),再重新生成并执行迁移:

# 删除错误迁移文件(替换为你实际的迁移文件名)
rm myapp/migrations/0013_mymodel_user.py

# 重新生成迁移文件
./manage.py makemigrations myapp

# 执行迁移
./manage.py migrate myapp

问题根源说明

之前的错误是因为Django生成外键约束时,默认使用default数据库的search_path=public,无法找到users表;指定db_table="auth.users"后,SQL会明确引用auth schema下的表。同时修正allow_migrate逻辑,避免Django尝试在default数据库创建不属于它的auth.users表。

内容的提问来源于stack exchange,提问作者tbhaxor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 01:08:22