我试图为与Google App引擎配合使用的WTForms制作一个独特的验证器。我有一个名为Question的模型和一个名为' slug'我需要独特。我在Stackoverflow上发现了这个非常好的例子,但是它使用了SQLAlchemy。我想看看是否有人可以帮我弄清楚如何使用Google App Engine而不是SQLAlchemy。
SQLAlchemy示例:Unique validator in WTForms with SQLAlchemy models
class Unique(object):
""" validator that checks field uniqueness """
def __init__(self, model, field, message=None):
self.model = model
self.field = field
if not message:
message = u'this element already exists'
self.message = message
def __call__(self, form, field):
check = self.model.query.filter(self.field == field.data).first()
if check:
raise ValidationError(self.message)
我认为"检查"需要更改行以使用GAE吗?但是我把这样的东西传递给对象并不是最好的。
我知道GAE查询会像...... Question.query(Question.slug = slug)
答案 0 :(得分:1)
我能够做到这一点......
class UniqueValidator(object):
""" validator that checks field uniqueness """
def __init__(self, model, field, message=None):
self.model = model
self.field = field
if not message:
message = u'Existing element with the same value.'
self.message = message
def __call__(self, form, field):
existing = self.model.query(getattr(self.model,self.field) == field.data).get()
if 'id' in form:
id = int(form.id.data)
else:
id = None
if existing and (id is None or id != existing.key.id()):
raise ValidationError(self.message)
和
class QuestionEditForm(Form):
id = HiddenField('id')
question = TextField('Question', [validators.Required(),
validators.Length(min=4, max=225)])
slug = TextField('Slug', validators = [validators.Required(),
validators.length(max=200),
UniqueValidator(
Question,
'slug',
'Existing slug with the same value.'
)])`enter code here`