django.db.utils.IntegrityError: (1062, “Duplicate

2019-05-31 01:28发布

I am using django multiple DB router concepts, having multiple sites with different db's. Base database user will login with all other sub sites.

When i try syncdb in base site its worked properly(at any time), but trying syncdb with other sites works first time only, if we try next time on-wards it throws integiry error like below

  • django.db.utils.IntegrityError: (1062, "Duplicate entry '22-add_somesame' for key 'content_type_id'")

Once i removed multiple DB router settings in that project means syncdb works properly(at any time).

So is this relates to multiple db router? or what else?

Please anyone advise on this, thanks.

1条回答
别忘想泡老子
2楼-- · 2019-05-31 01:56

The problem here is with the db router and django system objects. I've experienced the same issue with multiple DBs and routers. As I remember the problem here is with the auth.permission content types, which get mixed in between databases. The syncdb script otherwise tries to create these in all databases, and theb it creates permission content type for some object, which id is already reserved for a local model.

I have the following

BASE_DB_TYPES = (
 'auth.user',
 'auth.group',
 'auth.permission',
 'sessions.session',

)

and then in the db router:

def db_for_read(self, model, **hints):
    if hasattr(model, '_meta') and str(model._meta) in BASE_DB_TYPES:
        return 'base_db' # the alias of base db that will store users
    return None # the default database, or some custom mapping

EDIT:

Also, the exception might say that you're declaring a permission 'add_somesame' for your model 'somesame', while Django automatically creates add_, delete_, edit_ permissions for all objects.

查看更多
登录 后发表回答