static value list in model

I have a list of values which is not going to change.

Example:

modeofpayment : Cash, Cheque, OnlineTransfer, ATM Deposit

Is there a way without creating a database-table, I can use these values.

from django.db import models

# Create your models here.


class MasterCategory(models.Model):
	masterid = models.AutoField(primary_key=True)
	name = models.CharField(max_length=25, null=False)

	@property
	def __str__(self):
		return self.name


class PaymentMode(models.Model):
	modeid = models.AutoField(primary_key=True)
	name = models.CharField(max_length=10, null=False)

	@property
	def __str__(self):
		return self.name


class Daily(models.Model):
	transid = models.AutoField(primary_key=True)
	transdate = models.DateField()
	transdetails = models.CharField(max_length=25)
	transcategory = models.ForeignKey(MasterCategory, on_delete=models.CASCADE)
	transmode = models.ForeignKey(PaymentMode, on_delete=models.CASCADE)
	transsubdetails = models.CharField(max_length=100, null=True)
	transamount = models.FloatField()

	def __str__(self):
		return "%s %s %s %s %s %s %s" % (self.transid, self.transdate, self.transdetails, self.transcategory, self.transmode, self.transsubdetails, self.transamount)

Above is my current model ( database )
Instead of creating a table “PaymentMode”, is there a way I can use the values as I have mentioned above.

See Enumeration types as an other option.

(However, for a variety of reasons, I’m in favor of the “code table” approach.)

Could you elaborate a bit?

Sure - a “code table” is one of the informal / unofficial names for a table used to hold options, where the primary key of that table has some semantic meaning.

For example, the OP’s mode of payment table could be defined as:

class PaymentMode(models.Model):
    code = models.CharField(max_length=4, primary_key=True)
    display = models.CharField(max_length=10)

where the table may end up looking like:

 code  |  display
------------------
 cash  |  Cash
 chk   |  Cheque
 eft   |  Online Transfer
 atm   |  ATM Deposit

You can add additional columns if necessary, but you generally want to avoid that. (The purpose of these tables are not to provide data for processing, but to serve as validation of entered codes.)

Yes, you can end up with a fair number of tables that way. (By rough count, one system I work on has about 20 of them.) But I primarily work in areas where data integrity is an absolute requirement - and I frequently deal with data and data sources that can add data to the database outside Django’s control, and so need to ensure and enforce that integrity at the database layer.

1 Like