簡體   English   中英

如何在Web2py中的外鍵上添加NOT NULL約束

[英]How to add NOT NULL constraint on foreign keys in Web2py

我在使模型生成Web2py中不為null的外鍵時遇到麻煩。 我已經嘗試了所有我知道的東西以及可以在網上找到的所有東西。 這是一個簡單的示例:

db = DAL('sqlite://storage.db')
users=db.define_table('user', Field('name') )
cars=db.define_table('cars', Field('user', users, notnull=True), Field('Model') )
print db._lastsql

This print ===
CREATE TABLE cars(
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user INTEGER REFERENCES users(id) ON DELETE CASCADE,
    Model CHAR(512)
);
=============

看起來由於某種原因,web2py忽略了notnull = True。

我也嘗試了一些變通辦法,例如給default ='',但沒有幫助。 這是MySQL后端的另一個示例

db = DAL('mysql://test:test@localhost:3306/test')
db.define_table('property',
   Field('type', notnull=True),
   Field('area','integer', notnull=True),
   Field('rooms','integer', default = 0, notnull=True))

db.define_table('media',
   Field('title', length = 30),
   Field('file', 'upload', autodelete=True, notnull=True),
   Field('prop_id', db.property, notnull=True, default='', required=True))

CREATE TABLE SQL:
CREATE TABLE  `propdb`.`media` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(30) DEFAULT NULL,
  `file` varchar(512) NOT NULL,
  `prop_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `prop_id__idx` (`prop_id`),
  CONSTRAINT `prop_media_ibfk_1` FOREIGN KEY (`prop_id`) REFERENCES `prop_property` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8

在MySQL中,它不僅忽略了notnull,而且使列'DEFAULT NULL'變為了,正如您所看到的'prop_id'列一樣。 有人有什么主意嗎? 如何使web2py為外鍵添加“ NOT NULL”?

注意:如果刪除default ='',則沒有任何區別。 我根據@simplyharsh的建議和討論在此處http://www.mail-archive.com/web2py@googlegroups.com/msg12879.html上添加了它

設置notnull=True ,還應該設置默認屬性。

考慮一下這個線程

notnull =在web2pys DAL上下文中為True表示:

該字段的內容永遠不會為'null' (假),結果是,選擇字符串列將返回空字符串,整數或浮點列將返回值0而不是NULL(DAL:無或假)。

要強制web2py用戶插入值,您需要定義該字段的必需小部件。 例如:

db.tablefoo.fieldbar.requires = IS_IN_SET('OK', 'NOT OK')

我假設您不希望外鍵為null,因為它應該對應於已經存在的東西。 您是否嘗試過以下方法

db.property.area.requires=IS_IN_SET([Insert your list/array of possibilities])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM