[Django]-How can i create Generated/Computed column Postgres/DJANGO?

0๐Ÿ‘

Do you really need to have the result monto_stock stored in the database?

If no, then maybe just use a Python method/property on the class:

class Product(models.Model):
    name = models.CharField(max_length=200, null=True)
    precio_costo = models.FloatField(null=True)
    cantidad = models.IntegerField(null=True)

    @property
    def monto_stock(self):
        return self.precio_costo * self.cantidad

If yes, then maybe calculate the result in the models save() method:

class Product(models.Model):
    name = models.CharField(max_length=200, null=True)
    precio_costo = models.FloatField(null=True)
    cantidad = models.IntegerField(null=True)
    monto_stock = models.FloatField(null=True)

    def save(self, *args, **kwargs):
        self.monto_stock = self.precio_costo * self.cantidad
        super().save(*args, **kwargs)

Just be carefull: your fields allow NULL, so there will be errors if any field actually contains the value NULL (because you cannot do NULL/None multiplication in Python).

Do any of these options work for you?


EDIT: in case of option 1, to use the property monto_stock in your view you can simply access it like any other attribute of an model (but it will be read-only). For example:

# get a single product
p = Product.objects.first()
print(p.monto_stock)

# get sum of all products
print(sum(p.monto_stock for p in Product.objects.all()))

Just note that because it is a Python class property and not a DB field, it can NOT be used in database queries directly this way.

# will NOT work
print(Product.objects.aggregate(Sum('monto_stock'))))
๐Ÿ‘คRalf

0๐Ÿ‘

I have also find always_generated solution in django project website.
After trying so many things finally one approach works for me.

That is just REMOVE or COMMENT all those columns entry from models.py which have the db triggers.

Eg: auto increment columns, current timestamp columns, generated as columns etc.

# requesttimestamp = models.BigIntegerField(db_column='RequestTimeStamp', always_generated='createddate')  # Here I was getting that error.
# createddate = models.DateTimeField(db_column='CreatedDate', auto_now_add=True)

So I commented these two lines and it worked as expected.

Also no need to pass anything while creating instance to save record.

Leave a comment