database - 在 Django 中,如果使用原始 SQL 添加行,是否会使用列的默认值?

标签 database django postgresql

我注意到,在大多数情况下,Django 不会在数据库级别强制执行默认值。

模型中的字段定义:

description = models.TextField(default='')

SQL:

description | text   | not null

如果我使用原始 SQL 添加一行(如下所述: https://docs.djangoproject.com/en/dev/topics/db/sql/#executing-custom-sql-directly ),并且不包含具有默认值的字段的值,是否仍会使用默认值?

最佳答案

没有。

至少,不是基于我刚刚所做的测试。

模型.py:

class Recipient(models.Model):
    mailing = models.ForeignKey(Mailing, related_name="recipients")
    email = models.EmailField()
    how_sent = models.CharField(max_length=1, choices=SENT_TYPES, default="U")
    user = models.ForeignKey(User, blank=True, null=True)
    date_sent = models.DateTimeField(auto_now_add=True)
    date_viewed = models.DateTimeField(null=True, blank=True)

    def __unicode__(self):
        return "%s -> %s (%s)" % (self.mailing, self.email, self.date_sent)

然后我运行了这段代码:

>>> cursor.execute("""insert into mailings_recipient (mailing_id, email) values (3, '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="99edfceaedd9fce1f8f4e9f5fcb7f6ebfe" rel="noreferrer noopener nofollow">[email protected]</a>');""")
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "path/to/django/db/backends/util.py", line 40, in execute
    return self.cursor.execute(sql, params)
  File "/path/to/django-pyodbc/sql_server/pyodbc/base.py", line 326, in execute
    return self.cursor.execute(sql, params)
IntegrityError: ('23000', "[23000] [FreeTDS][SQL Server]Cannot insert the value NULL into column 'how_sent', table 'database.dbo.mailings_recipient'; column does not allow nulls. INSERT fails. (515) (SQLExecDirectW)")

如果 Django 为您输入默认值,它会为 how_sent 发送值“U”,但我收到了错误。

然后如果我们使用 Django 创建一条记录,

Recipient.objects.create(mailing=Mailing.objects.all()[0], email='<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="80f4e5f3f4c0e5f8e1edf0ece5aeeff2e7" rel="noreferrer noopener nofollow">[email protected]</a>') 

这是对应的SQL:

SET NOCOUNT ON INSERT INTO [mailings_recipient] ([mailing_id], [email], [how_sent], [user_id], [date_sent], [date_viewed]) VALUES (1, <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="afdbcadcdbefcad7cec2dfc3ca81c0ddc8" rel="noreferrer noopener nofollow">[email protected]</a>, U, None, 2012-09-14 14:48:59, None) 
;SELECT SCOPE_IDENTITY()

因此,如果您确实询问如果您使用诸如 cursor.execute("INSERT INTO...") 之类的内容,是否会为您输入默认值,那么答案是,它不会为您设置这些默认值。正如您所指出的,Django 在创建数据库模式时不会为您设置默认值,它只是在执行正常保存时设置这些默认值。

关于database - 在 Django 中,如果使用原始 SQL 添加行,是否会使用列的默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12430614/

相关文章:

python - 如何从文件中执行 manage.py 命令

java - 为什么hibernate在insert和delete操作时会生成 'T_' prefix tableName?

database - 任何可扩展的 OLAP 数据库(网络应用程序规模)?

python - Django form.errors 没有出现在模板中

python - 如何检查 Django 模板中的多重性

sql - 在sql中堆叠来自不同表的多列

codeigniter - 使用 If 语句隐藏/删除/移除列 codeigniter 的字段

java - 如何在 jquery 数据表中显示 json 数据

mysql - AWS DMS - MYSQL 上的 CDC 作为源端点的微秒级精度

java - 如何使用 JDBC 将 Java 应用程序连接到 db4free.net?