在一对多关系中限制或截断子代数的首选/有效方法是什么。假设我有2个简单的flask-sqlalchemy模型,例如:
MAX_CHILDREN = 5
class Parent(db.Model):
__tablename__ = "Parent"
id = db.Column(db.Integer, primary_key=True)
children = db.relationship("Child", cascade="all, delete-orphan", backref="parent")
def truncate_children(self):
self.children = self.children[-MAX_CHILDREN:]
class Child(db.Model):
__tablename__ = "Child"
id = db.Column(db.Integer, primary_key=True)
parent_id = db.Column(db.Integer, db.ForeignKey('Parent.id'))
Parent.truncate_children
是限制已保存子代数量的最有效方法,还是有本机内置的方法来实现我错过的目标?