I am new to Django and new to Python. I decided to build a project to practise my understanding.
Anyway while designing my tables what I found is that I would like to have a field in there that is calculated through say a python function. I read through and found that I could potentially use @property decorator and setter.
ref: [https://www.stavros.io/posts/how-replace-django-model-field-property/](http://How to replace a Django model field with a property)
So in my model class I have:
class CapacityRequest(models.Model):
cr = models.IntegerField(verbose_name="Change Request No")
disktier = models.ForeignKey('Disktier', on_delete=models.SET_DEFAULT,default=1)
requestedby = models.CharField(max_length=50, verbose_name='Requested By')
datacentre = models.ForeignKey('Datacentre', on_delete=models.SET_DEFAULT,default=1)
storageresource = models.CharField(max_length=50, verbose_name='VM Name/Datastore/Lun')
vcpu = models.IntegerField(default=0)
ram = models.IntegerField(default=0)
requestdate = models.DateTimeField(auto_now=True,verbose_name="Request Date")
notes = models.CharField(max_length=80)
diskspacegb = models.IntegerField(default=0)
_diskspace_gb_vswap = models.DecimalField(db_column="diskspace_gb_vswap", decimal_places=2 , max_digits=10)
@property
def diskspace_gb_vswap(self):
return self._diskspace_gb_vswap
@diskspace_gb_vswap.setter
def diskspace_gb_vswap(self , value):
self._diskspace_gb_vswap = self.diskspacegb * 1.5
In the shell
I import the necessary classes and after getting the object details for the foreign keys run this in the django shell to see if it will work.
capacityrequest = CapacityRequest(cr = 2353253 , disktier = ssddatastore , storageresource = âVMTestâ , diskspacegb = 60)
then
capacityrequest.save()
However i am getting an error that says:
django.db.utils.IntegrityError: NOT NULL constraint failed: capacityrequest_capacityrequest.diskspace_gb_vswap
This tells me that the function setters and such is not being implemented properly.
Any help to achieve what i want to do would be most appreciated.