[英]Flask SQLAlchemy: How to find the primary key value before adding a new object to the session?
我正在使用b64encode
從表中每一行的主鍵創建一個唯一的引用字符串。 這是我在 Flask SQLAlchemy 中的 model:
class Groups(db.Model):
id = db.Column(db.Integer, primary_key = True)
ref_id = db.Column(db.String(20), index = True)
def __init__(self):
self.ref_id = id_encode(self.id)
但是,傳入self.id
id_encode()
function 的 self.id 具有“無”值,而不是主鍵的值。 據我所知,只有在提交 session 或使用 flush() 方法后才能獲得新的主鍵值。
這是id_encode()
的定義:
def id_encode(num):
bts = base64.b64encode(bytes(str(num), 'utf-8'))
print(num)
return bts.decode()
如果有什么方法可以讓它工作,或者有什么更好(但簡單)的方法來生成唯一參考 ID? 我只是不希望普通用戶能夠通過輸入數字 ID 導航到其他組。
您可以做的是用 class function 替換 « __init __ »。
所以而不是:
class Groups(db.Model):
id = db.Column(db.Integer, primary_key = True)
ref_id = db.Column(db.String(20), index = True)
def __init__(self):
self.ref_id = id_encode(self.id)
你應該試試:
class Groups(db.Model):
id = db.Column(db.Integer, primary_key = True)
ref_id = db.Column(db.String(20), index = True)
def generate_id(self):
self.ref_id = base64.b64encode(bytes(str(self.id), 'utf-8'))
然后當您創建一個新組 object 時,請記住在提交之前使用 function。
group = Groups(id=xxx, arg2=xxx, arg3=xxx etc)
# omit "id" if you set it to autoincrement
group.generate_id()
db.session.commit()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.