How to Add a Price Field to a Database Table in Django 


               


How to Add a Price Field to a Database Table in Django



Python


In this article, we show how to add a price field (column) to a database table in Django.

Now Django does not have a built-in Price Field; however, a field which simulates money in Django can be easily created using the DecimalField.

Django's DecimalField requires 2 parameters, one is max_digits and the other is decimal_places.

max_digits is the total number of digits that is in the number specified. So, for a number such as 999.99, the max_digits would be 5.

And because you're dealing with currency (money), the decimal_places will always be set equal to 2 for a price field.

So below is the code for a database table called Product (stores inventory) and it has a item and a price field.



We'll now go over the code.

So, like any database table creation, we import models from django.db

We create a database table called Product, an instance of the Model class.

We then create a field called item of type CharField and set it equal to a max_length of 200 characters.

We then create our price field.

The price field is a DecimalField.

We can make the max_digits be anything you want. In this case, I set it to 10.

The max_digits is the total number of digits in the number entirely, including the decimal.

So this means that in the code above, the maximum price of an item can be 99,999,999.99 (99 million dollars).

If you're running a simple clothing store website or such, you wouldn't even need a value of this size. However, you can do it just for protection.

A max_digits of 3 allows prices up to $9.99

A max_digits of 4 allows prices up to $99.99

A max_digits of 5 allows prices up to $999.99

A max_digits of 6 allows prices up to $9,999.99

A max_digits of 7 allows prices up to $99,999.99

A max_digits of 8 allows prices up to $999,999.99

A max_digits of 9 allows prices up to $9,999,999.99

Again, there's no issue with making it greater than the amount you need, but don't make it lower than the amount you need. Put a higher value just for protection.

Of course, decimal_places will always be 2 to replicate currency.

If you enter an integer into the price field, then Django will just convert it to a decimal. So, if you enter 143, for instance, Django will convert this value to 143.00 in the database table.

And this is how you can replicate a price field in a database table in Django.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...