【发布时间】:2018-08-25 08:27:37
【问题描述】:
我有以下 django 数据模型
class ApiLog(models.Model):
name = models.TextField(blank=False, null=False)
ts = models.DateTimeField(default=timezone.now, blank=False, null=False)
ip_address = models.GenericIPAddressField(blank=True, null=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
以数据库结束
django=# \d+ users_apilog
Table "public.users_apilog"
Column | Type | Collation | Nullable | Default | Storage | Stats target | Description
------------+--------------------------+-----------+----------+------------------------------------------+----------+--------------+-------------
id | integer | | not null | nextval('users_apilog_id_seq'::regclass) | plain | |
name | text | | not null | | extended | |
ts | timestamp with time zone | | not null | | plain | |
ip_address | inet | | | | main | |
user_id | integer | | not null | | plain | |
Indexes:
"users_apilog_pkey" PRIMARY KEY, btree (id)
"users_apilog_user_id_2eb2b1cf" btree (user_id)
Foreign-key constraints:
"users_apilog_user_id_2eb2b1cf_fk_users_user_id" FOREIGN KEY (user_id) REFERENCES users_user(id) DEFERRABLE INITIALLY DEFERRED
因此,非 django 应用程序也将访问此表。我需要确保自动时间戳生成(对于列 ts)完全由 postgres 处理,而不是 python。
我不希望有
Column | Type | Collation | Nullable | Default | Storage | Stats target | Description
------------+--------------------------+-----------+----------+---------+---------+--------------+-------------
ts | timestamp with time zone | | not null | | plain | |
我希望有
Column | Type | Collation | Nullable | Default | Storage | Stats target | Description
------------+--------------------------+-----------+----------+---------+---------+--------------+-------------
ts | timestamp with time zone | | not null | now() | plain | |
我曾尝试过其他技术,例如 auto_now=True、auto_now_add=True、...
但是,它们都没有生成我想要的表模式。通过使用以下任何生成的表架构,其default 列仍然为空。
default=timezone.nowauto_now=Trueauto_now_add=True
【问题讨论】:
-
defaults 不是由数据库填写,而是由 Django 填写。 -
@WillemVanOnsem 是的。我知道。我想让它由数据库填充。有什么办法吗?
-
@CheokYanCheng:那是不是 BearBrown,BearBrown实际上发布了一个sensical副本。
标签: python django postgresql