Hello, everyone.
I am facing a pitfall with calling custom validation function within serializer.
Here is the full scrutiny:
- I have 2 linked models in my project – Borrowing and Payment. And I have certain business logic – in case there are still payments with pending status (unpaid payments) user can’t create new Borrowing in a system.
- For that purpose, I have custom validation method within my Borrowing model:
class Borrowing(models.Model):
borrow_date = models.DateField(auto_now_add=True)
expected_return_date = models.DateField()
actual_return_date = models.DateField(null=True, blank=True)
book = models.ForeignKey(
Book,
on_delete=models.CASCADE,
related_name="borrowings"
)
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name="borrowings"
)
@staticmethod
def validate_pending_payment(user, error_to_raise):
borrowings = user.borrowings.all()
pending_payments = []
for borrowing in borrowings:
pending_payments.extend(borrowing.payments.filter(status="PN"))
if pending_payments:
raise error_to_raise("You have not yet completed your paying. "
"Please complete it before borrowing a new book.")