为什么我的逻辑不能验证我的自定义用户模型中名为formattedusername的字段是否等于使用下面定义的def cfo的字段my QvDatareducecfo模型。
class User(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=7, unique=True)
formattedusername = models.CharField(max_length=11, unique=True, primary_key = True)
first_name = models.CharField(max_length=40)
last_name = models.CharField(max_length=140)
date_joined = models.DateTimeField(default=timezone.now)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_cfo = models.BooleanField(default=False)
USERNAME_FIELD = 'username'
class Meta:
app_label = 'accounts'
db_table = "user"
def save(self, *args, **kwargs):
self.formattedusername = '{domain}\{username}'.format(
domain='HCA', username=self.username)
super(User, self).save(*args, **kwargs);
def cfo(self):
cfo = self.QvDatareducecfo.cfo_ntname
if self.formattedusername == cfo:
self.is_cfo = 1
else:
self.is_cfo = 0
print (is_cfo)
super(User, self).save(is_cfo)
# REQUIRED_FIELDS = "username"
def __str__(self):
return "@{}".format(self.username)
我将cfo_ntame字段定义为QvDatareducecfo模型中的OneToOneField。我没有在我的逻辑上收到错误消息,看起来返回is_cfo打印0,但如果我将cfo表更新为1并重新登录它不会更新为0和用户ID我是使用未列在cfo表中。
QvDatareduceCfo Model:
class QvDatareducecfo(models.Model):
cfo_ntname = models.OneToOneField(settings.AUTH_USER_MODEL,db_column='CFO_NTName',primary_key=True, serialize=False, max_length=7) # Field name made lowercase.
cfo_type = models.IntegerField(db_column='CFO_Type', blank=True, null=True)
class Meta:
managed = False
db_table = 'QV_DataReduceCFO'
答案 0 :(得分:1)
有两个问题需要解决,
如果没有为OneToOneField指定related_name参数, Django将使用当前模型的小写名称作为 默认值。所以改为
def cfo(self):
cfo = self.qvdatareducecfo.cfo_ntname
如果您在访问self.qvdatareducecfo时遇到RelatedObjectDoe sNotExist错误,则必须创建qvr记录并设置对相应“用户”的引用。记录。 例如:
QV = QvDatareducecfo() qv.cfo_ntname = user qv.save()