如何在CREATE TABLE结束时添加DEFAULT CONSTRAINT?
我想在最后有一个独立的行,如
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(
verbose_name=_('Email'), max_length=255, unique=True
)
first_name = models.CharField(verbose_name=_('First Name'),
max_length=50)
last_name = models.CharField(verbose_name=_('Last Name'),
max_length=50)
is_active = models.BooleanField(verbose_name=_('Active'),
default=True)
is_staff = models.BooleanField(verbose_name=_('Staff'),
default=False)
is_verify = models.BooleanField(verbose_name=_('Verify'),
default=False)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']
class Meta:
verbose_name = _('User')
verbose_name_plural = _('Users')
def __str__(self):
return self.get_full_name()
def get_full_name(self):
return '{first_name} {last_name}'.format(
first_name=self.first_name, last_name=self.last_name
)
def get_short_name(self):
return '{first_name}'.format(first_name=self.first_name)
def activation_key():
while True :
key = (''.join(choice(hexdigits) for i in range(50)))
if ActivationKey.objects.filter(key=key).count() == 0:
return key
class ActivationKey(models.Model):
user = models.ForeignKey(verbose_name=_('User'), to='users.User',
related_name='activatio_with_mail')
is_used = models.BooleanField(verbose_name=_('Used'),
default=False)
key = models.CharField(verbose_name=_('Key'), max_length=50,
unique=True)
class Meta:
verbose_name = _('ActivationKey')
verbose_name_plural = _('ActivationKey')
def __str__(self):
return self.key
def save(self, *args, **kwargs):
if not self.pk:
self.key = activation_key()
super(ActivationKey, self).save(*args, **kwargs)
它无法正常工作。我收到错误消息
你可以帮帮我吗?非常感谢前进!'附近的语法不正确。
答案 0 :(得分:0)
您应该只使用默认值旁边的默认值,例如:
CREATE TABLE myTable (
table_id INT NOT NULL,
firstColumn NVARCHAR(10),
secondColumn INT DEFAULT 0,
thirdColumn INT
)
或者,如果您确实要添加约束,可以稍后使用ALTER TABLE
添加约束:
CREATE TABLE myTable (
table_id INT NOT NULL,
firstColumn NVARCHAR(10),
secondColumn INT,
thirdColumn INT
)
ALTER TABLE myTable ADD CONSTRAINT DEF_secColumn DEFAULT 0 FOR [secondColumn]
或@ jeroen-mostert建议的第三个选项
CREATE TABLE myTable (
table_id INT NOT NULL,
firstColumn NVARCHAR(10),
secondColumn INT CONSTRAINT DEF_secColumn DEFAULT 0,
thirdColumn INT
)