Validasi kustom sekarang harus dilakukan oleh mengimplementasikan clean()
metode pada model
.
class Essay(Document):
status = StringField(choices=('Published', 'Draft'), required=True)
pub_date = DateTimeField()
def clean(self):
"""
Ensures that only published essays have a `pub_date` and
automatically sets the pub_date if published and not set.
"""
if self.status == 'Draft' and self.pub_date is not None:
msg = 'Draft entries should not have a publication date.'
raise ValidationError(msg)
# Set the pub_date for published items if not set.
if self.status == 'Published' and self.pub_date is None:
self.pub_date = datetime.now()
Sunting: Karena itu, Anda harus berhati-hati menggunakan clean()
seperti yang dipanggil dari validate()
sebelum memvalidasi model berdasarkan aturan yang ditetapkan dalam definisi model Anda.