Now, let's write code that will make sure whenever a Library Membership is created, there is no active membership for the Member.
library_membership.py
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class LibraryMembership(Document):
# check before submitting this document
def before_submit(self):
exists = frappe.db.exists(
"Library Membership",
{
"library_member": self.library_member,
# check for submitted documents
"docstatus": 1,
# check if the membership's end date is later than this membership's start date
"to_date": (">", self.from_date),
},
)
if exists:
frappe.throw("There is an active membership for this member")
We wrote our logic in the before_submit
method which will run before we submit
the document. We used the frappe.db.exists
method to check if a Library
Membership record exists with our provided filters. If it exists, we used
frappe.throw
to stop the execution of program with a message that will show up
letting the user know the reason.
Now, try creating a Library Membership with an overlapping period and you should see an error when you submit the document.