'How to use validator in Django depending on the database data?

I'm making a web app that keeps tracks of a small business. For that purpose I have two models designed in my app. One of which is all the storage information and the other is for each selling orders, like:

class Storage(models.Model):
    name = models.CharField('product name', max_length=64)
    quantity = models.DecimalField('inventory', max_digits=6, decimal_places=4, default=0)

class Orders(models.Model):
    product = models.ForeignKey('Storage', on_delete=models.CASCADE)
    volumn = models.DecimalField('order volumn', max_digits=6, decimal_places=4, default=0)

I want a validator for my Orders class so that the input value for 'volumn' from the form doesn't exceed the corresponding quantity data in the Storage class. How can I achieve that? Thanks!



Solution 1:[1]

welcome to StackOverlow. This is my first answer so if it works i would appreciate if you can click "accept as answer"

You can use clean() method for your model. More here:

https://docs.djangoproject.com/en/dev/ref/models/instances/?from=olddo#id1

from django.db import models 
from django.core.exceptions import ValidationError

class Storage(models.Model):
    name = models.CharField('product name', max_length=64)
    quantity = models.DecimalField('inventory', max_digits=6, decimal_places=4, default=0)

class Orders(models.Model):
    product = models.ForeignKey('Storage', on_delete=models.CASCADE,related_name='storage')
    volumn = models.DecimalField('order volumn', max_digits=6, decimal_places=4, default=0)

    def clean(self):
        # Don't allow volumn to be bigger than quantity in Storage
        if  self.volumn > self.product.quantity :
            raise ValidationError({'volumn': ('Volumn cannot be bigger than storage quantity')})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1