我的django项目实现了一个自定义用户模型(MyUser)。它还为我的自定义用户实现了一个proxymodel(MyUserProxy),我想使用proxymodel从我的数据库中删除用户。见模型&经理下面,
项目/帐户/ models.py
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from django.db import models
from .managers import MyUserManager
class MyUser(AbstractUser, PermissionsMixin):
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
username = models.CharField(max_length=255, unique=True)
email = models.CharField(max_length=255, unique=True)
...
objects = MyUserManager()
class Meta():
verbose_name = _('My user')
verbose_name_plural = _('My users')
def __unicode__(self):
return self.username
class MyUserProxy(MyUser):
class Meta():
proxy = True
项目/帐户/ managers.py
from django.contrib.auth.models import UserManager
class MyUserManager(UserManager):
def __init__(self, *args, **kwargs):
super(MyUserManager, self).__init__(*args, **kwargs)
我项目中的其他几个应用程序与我的自定义用户(MyUser)之间存在ForeignKey关系,因此当我删除用户时,与该用户相关的记录也会被删除。当我将settings.py中的AUTH_USER_MODEL指定为MyUser时,此工作正常,相关应用程序的记录将被用户删除。
项目/示例/ settings.py
AUTH_USER_MODEL = 'account.MyUser'
然而,当我使用MyUserProxy作为AUTH_USER_MODEL时,我收到错误,
OperationalError: (1054, "Unknown column 'otherapp.myuserproxy_id'
in 'where clause'")
Django似乎认为应用程序“otherapp”的ForeignKey数据库列是“myuserproxy_id”,而实际上它是“myuser_id”,因为模型MyUser指定了它。为什么django将我的proxymodel(MyUserProxy)的名称与数据库列相关联?
https://docs.djangoproject.com/en/dev/topics/db/models/#proxy-models
答案 0 :(得分:0)
事实证明,我的otherapp模型与AUTH_USER_MODEL有一个ManyToMany关系。 ManyToMany关系获取从proxymodel名称(myproxuuser_id)派生的列名称,而ForeignKey关系从被代理的模型(myuser_id)获取列名称。 Otherapp使用迁移,因此未发生列名“myuser_id”的更改,从而导致OperationalError。为了澄清,我已将模型和结果数据库结构放在下面,
项目/ X / settings.py
INSTALLED_APPS = ()
'A',
'B',
)
AUTH_USER_MODEL = 'A.Aproxy'
项目/ A / models.py
from django.db import models
class A(models.Model):
USERNAME_FIELD = 'field1'
REQUIRED_FIELDS = ['field2']
field1 = models.CharField(max_length=255, unique=True)
field2 = models.CharField(max_length=255, unique=True)
def __init__(self, *args, **kwargs):
super(A, self).__init__(*args, **kwargs)
class AProxy(A):
class Meta():
proxy = True
项目/ B / models.py
from django.db import models
from django.conf import settings
from A.models import A
class B(models.Model):
a = models.OneToOneField(settings.AUTH_USER_MODEL)
field1 = models.CharField(max_length=255, unique=True)
field2 = models.CharField(max_length=255, unique=True)
mtm = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='mtm')
def __init__(self, *args, **kwargs):
super(B, self).__init__(*args, **kwargs)
表结构中的结果
A_a
+----+--------+--------+
| id | field1 | field2 |
+----+--------+--------+
B_b
+----+------+--------+--------+
| id | a_id | field1 | field2 |
+----+------+--------+--------+
B_b_mtm
+----+------+-----------+
| id | b_id | aproxy_id |
+----+------+-----------+
| 1 | 1 | 1 |
+----+------+-----------+
为什么django为ManyToMany字段应用了不同的列名,但我不清楚。