如何将django auth从mongo迁移到SQL? (Mongo上的ManyRelatedManger)

时间:2011-12-03 21:02:42

标签: django mongodb

我有多个数据库。遗留的Mongo数据库,'mongo'和我迁移到的新PostgreSQL数据库'sql'。我试图移动所有用户及其权限。

在代码中,我已经将权限从'mongo'移到'sql'。

users = User.objects.using('mongo').all().values('username')
for user in users:
    u = User.objects.db_manager('sql').create_user(user.username, user.email, user.password)
    # Where the ManyRelatedManager trouble begins
    # This error is "'dict' object has no attribute 'user_permissions'"
    u.user_permissions.add(user.user_permissions)
    # This error is "This query is not supported by the database." on the .all()
    old_permissions = user.user_permissions.all()
    for p in old_permissions:
         new_permission = Permission.objects.using('sql').get(name=p.name)
         u.user_permissions.add(new_permission)
         u.save()

由于Mongo不喜欢加入,我如何访问用户的Permission对象?

1 个答案:

答案 0 :(得分:1)

因此,如果我查看我的django项目(sqlite3),则在同步auth应用程序时会创建7个表。我将看一下如何在标准的django应用程序中创建每个应用程序

auth_group         
auth_group_permissions
auth_message
auth_permission
auth_user
auth_user_groups
auth_user_user_permissions

如果我显示它们的架构,它看起来像这样:

CREATE TABLE "auth_group" (
    "id" integer NOT NULL PRIMARY KEY,
    "name" varchar(80) NOT NULL UNIQUE
);
CREATE TABLE "auth_group_permissions" (
    "id" integer NOT NULL PRIMARY KEY,
    "group_id" integer NOT NULL,
    "permission_id" integer NOT NULL REFERENCES "auth_permission" ("id"),
    UNIQUE ("group_id", "permission_id")
);
CREATE TABLE "auth_message" (
    "id" integer NOT NULL PRIMARY KEY,
    "user_id" integer NOT NULL REFERENCES "auth_user" ("id"),
    "message" text NOT NULL
);
CREATE TABLE "auth_permission" (
    "id" integer NOT NULL PRIMARY KEY,
    "name" varchar(50) NOT NULL,
    "content_type_id" integer NOT NULL,
    "codename" varchar(100) NOT NULL,
    UNIQUE ("content_type_id", "codename")
);
CREATE TABLE "auth_user" (
    "id" integer NOT NULL PRIMARY KEY,
    "username" varchar(30) NOT NULL UNIQUE,
    "first_name" varchar(30) NOT NULL,
    "last_name" varchar(30) NOT NULL,
    "email" varchar(75) NOT NULL,
    "password" varchar(128) NOT NULL,
    "is_staff" bool NOT NULL,
    "is_active" bool NOT NULL,
    "is_superuser" bool NOT NULL,
    "last_login" datetime NOT NULL,
    "date_joined" datetime NOT NULL
);
CREATE TABLE "auth_user_groups" (
    "id" integer NOT NULL PRIMARY KEY,
    "user_id" integer NOT NULL,
    "group_id" integer NOT NULL REFERENCES "auth_group" ("id"),
    UNIQUE ("user_id", "group_id")
);
CREATE TABLE "auth_user_user_permissions" (
    "id" integer NOT NULL PRIMARY KEY,
    "user_id" integer NOT NULL,
    "permission_id" integer NOT NULL REFERENCES "auth_permission" ("id"),
    UNIQUE ("user_id", "permission_id")
);

启用auth app后,使用syncdb在新数据库中创建这些表,然后迭代mongo版本中的文档。对于每个文档,在SQL-land中填充适当的表。