django - 无法使用数据库路由器使用save_model保存

标签 django django-models django-forms django-admin

我正在使用数据库路由器,因此我的应用程序有两个数据库。一个数据库用于默认django数据,另一个数据库。

在我的管理员中,我已重写save_model函数以保存created_by变量,但是我无法做到这一点。

Cannot assign "<User: testuser>": the current database router prevents this relation.

数据库路由器:
from django.conf import settings

    class DatabaseAppsRouter(object):
        def db_for_read(self, model, **hints):
            """Point all read operations to the specific database."""
            if settings.DATABASE_APPS_MAPPING.has_key(model._meta.app_label):
                return settings.DATABASE_APPS_MAPPING[model._meta.app_label]
            return None

        def db_for_write(self, model, **hints):
            """Point all write operations to the specific database."""
            if settings.DATABASE_APPS_MAPPING.has_key(model._meta.app_label):
                return settings.DATABASE_APPS_MAPPING[model._meta.app_label]
            return None

        def allow_relation(self, obj1, obj2, **hints):
            """Allow any relation between apps that use the same database."""
            db_obj1 = settings.DATABASE_APPS_MAPPING.get(obj1._meta.app_label)
            db_obj2 = settings.DATABASE_APPS_MAPPING.get(obj2._meta.app_label)
            if db_obj1 and db_obj2:
                if db_obj1 == db_obj2:
                    return True
                else:
                    return False
            return None

        def allow_syncdb(self, db, model):
            """Make sure that apps only appear in the related database."""
            if model._meta.app_label in ['south']:
                return True;
            elif db in settings.DATABASE_APPS_MAPPING.values():
                return settings.DATABASE_APPS_MAPPING.get(model._meta.app_label) == db
            elif settings.DATABASE_APPS_MAPPING.has_key(model._meta.app_label):
                return False
            return None

行政:
class SomeEntityAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        user = request.user._wrapped if hasattr(request.user,'_wrapped') else request.user
        if not obj.created_by:
            obj.created_by = user
            obj.save()

我什至尝试通过使用save(using='thedb')定义其他数据库,但这也不起作用。我的数据库路由器错了吗?

最佳答案

您遇到的问题是由于难以存储存储在两个不同数据库中的对象之间的关系而引起的。在您的示例中,您声明已创建一个数据库来存储所有Django贡献的对象,其中包括由auth应用程序创建的User对象。同时,第二个模型的对象将存储在一个独特且完全独立的数据库中。当您尝试在一个数据库中存储的新对象和User对象之间创建关系时,您正在尝试跨数据库关系。
跨数据库关系是一个难题,在Django中使用多个数据库时尚未解决。如果您需要有关此问题的更多信息,请添加the Django documentation has a brief note about this problem(为清楚起见,已在下面复制)。

Django doesn’t currently provide any support for foreign key or many-to-many relationships spanning multiple databases. If you have used a router to partition models to different databases, any foreign key and many-to-many relationships defined by those models must be internal to a single database.

This is because of referential integrity. In order to maintain a relationship between two objects, Django needs to know that the primary key of the related object is valid. If the primary key is stored on a separate database, it’s not possible to easily evaluate the validity of a primary key.

If you’re using Postgres, Oracle, or MySQL with InnoDB, this is enforced at the database integrity level – database level key constraints prevent the creation of relations that can’t be validated.

However, if you’re using SQLite or MySQL with MyISAM tables, there is no enforced referential integrity; as a result, you may be able to ‘fake’ cross database foreign keys. However, this configuration is not officially supported by Django.

关于django - 无法使用数据库路由器使用save_model保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26579231/

相关文章:

python - django:为可以是作家或 Actor 或两者的人创建模型

django预先填充modelform-什么也没发生

css - 使用 Django ModelForm 时标记必填字段的标签

python - Django request.POST.get SQL注入(inject)

python - 为什么显示此错误 'function' 对象没有属性 'as_view'

python - 在 Django 中将 Self 定义为多个属性

Django:在保存之前将模型对象分配为外键

python - 使用 django 将 python 集存储在数据库中

python - Django模型表单保存, 'int'对象没有属性 'save'

Django - 即使在 POST 上没有更改任何字段,也保存 modelForm