Python Django Model Example

Model is generally used to represent database table data. It contains the basic fields and behaviors of the data you are storing. Django provides structured data processing and operation processing for your network applications through the abstract model layer (models). Database-related code is generally written in models.py. Django supports SQLite3, MySQL, PostgreSQL and other databases, you can use Django database api to insert, delete, modify and select the database table data.

1. Configure Database Connection Settings.

Before you can process database operation in Django, you need to configure related database connection information in settings.py file. Below configuration will connect to mysql server that run on localhost and listening on port 3306.

DATABASES = {
        'default': {
             'ENGINE': 'django.db.backends.mysql', # mysql database python driver.
             'NAME': 'employee',    # mysql database name.
             'USER': 'root',   # db login user name.
             'PASSWORD': '', # db login user password.
             'HOST': '', # db machine ip or domain, if left empty then the value is localhost.
             'PORT': '3306', # db server listening port number
         }
}

SQLite db is the default built-in db which Django uses. And the SQLite db engine name is django.db.backends.sqlite3. Below is an example of SQLite db settings.

PROJECT_DIR = os.path.abspath(os.path.dirname(__file__))
    DATABASES = {
    'default': {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': os.path.join(PROJECT_DIR, 'employee.db'),
    }
}

1.1 Django DB Settings Issues.

  1. The NAME is the name of the database that must be created before mysql connects, while sqlite database above is created automatically at runtime.
  2. After setting up, we need to activate mysql before starting our Django project.
  3. When the project is started an error like no module named MySQLdb may be thrown.
  4. This is because Django uses MySQLdb by default, but MySQLdb has a big problem with Python3, so the driver we need is PyMySQL which is compatible with Python 3.
  5. So, we need to find the project __init__ file and write below code in it.
    import pymysql
    pymysql.install_as_MySQLdb()

2. Model Field Type.

  1. AutoField : IntegerField that grows automatically based on the actual id. You usually don’t need to use it directly. If not specified, the value will be automatically increased.
  2. BigIntegerField : A 64-bit integer, similar to an IntegerField, whose default form widget is a TextInput .
  3. IntegerField([**options]) : An integer. In all databases supported by Django, values ranging from -2147483648 to 2147483647 are valid. The default form input widget is TextInput.
  4. BinaryField : The Field used to store the original binary code. Bytes assignment is only supported. Note that this Field has only a limited amount of functionality. For example, it is unlikely to query on data with a BinaryField value.
  5. BooleanField : True/false fields. The default form widget is a CheckboxInput. If you need to set null value, use NullBooleanField instead of BooleanField. If Field.default is not specified, BooleanField default value is None.
  6. CharField : Is a place to store strings of varying lengths from small to large. If it’s a large text type, you can use a TextField. The default form widget for this field is TextInput. CharField must accept an additional parameter. CharField.max_length : the maximum character length. max_length will play a role in the database layer and Django form validation, used to limit the length of the field.
  7. DateField : This is a date represented by Python’s datetime.date instance. DateField.auto_now automatically sets the field to the current time each time the object is saved. It is used to create timestamp for “last modification”. Notice that it always uses the current date. It’s not a default value, you can override it at any time. DateField.auto_now_add automatically sets the current time when an object is first created. It always use the current date. The default form control for this field is a TextInput. A javascript-written calendar control is added to the admin site, and a “Today” shortcut button contains an additional invalid_date error message key also be added in the web page.
  8. DateTimeField(DateField) : Date + Time Format YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ].
  9. DateField(DateTimeCheckMixin, Field) : Date Format YYYY-MM-DD.
  10. TimeField(DateTimeCheckMixin, Field) : Time Format HH:MM[:ss[.uuuuuu]].
  11. DurationField(Field) : This is a Field type used to store data for a period of time – similar to timedelta in Python. It’s value is a long integer time interval, stored in the database as bigint, the value obtained in ORM is datetime.timedelta type.
  12. DecimalField(max_digits=None, decimal_places=None[, **options]) : represents the decimal floating point number.
  13. EmailField([max_length=254, **options]) : Is a CharField’s sub type, it is used to check whether the email address entered is valid or not. It uses the EmailValidator to validate the input.
  14. FileField([upload_to=None, max_length=100) : A field that uploads a file. FileField fields do not support primary_key and unique parameters, and TypeError is generated if used.
  15. FilePathField (path = None [, match = None, recursive = False, max_length = 100]) : A CharField whose value is limited to the file name and path of a specific directory within the file system. There are three parameters, the first parameter is required.
  16. FloatField([**options])  : An instance of Python float used to represents a floating-point number.
  17. ImageField([upload_to=None, height_field=None, width_field=None, max_length=100, **options]) : Inherits all FileField properties and methods, but also validates the uploaded object to ensure that it is a valid image.
  18. TextField([**options]) : Large Text Field. The default form component for this model is the Textarea.
  19. TimeField([auto_now=False, auto_now_add=False, **options]) : The time field, which is the same as datetime.time in Python. Accept the same auto-fill option as DateField. The default form component is TextInput.
  20. URLField([max_length=200, **options]) : A CharField type and the value is a URL. The default form widget for this field is TextInput.
  21. UUIDField([**options]) : A field used to store the UUID. When using a PostgreSQL database, the data type in the database corresponding to this field type is a UUID.

3. Field Type Optional Parameters.

  1. Field.null : If True, Django stores null values in the database. The default value is False.
  2. Field.blank : If True, this Field is allowed to be blank. The default value is False.
  3. Field.choices : This is an iterable structure (for example, a list or tuple). Consists of iterable binary groups (e.g. [(A, B), (A, B)…) ) to provide a selection for this field. If you set choices value, then the default table style will display a selection box instead of the standard text box, and the selection box item values will be tuples value in the choices.
  4. Field.db_column : The name used in the database to represent the Field. If not specified, Django will use the Field name as the database table column name.
  5. Field.db_index : If True, django-admin sqlindexes will print a CREATE INDEX statement for this Field.
  6. Field.error_messages : Allows you to override the default error messages thrown. Identify the error message you want to override by specifying the key.
  7. Field.primary_key : If True, the Field becomes the primary key Field of the model. If you do not specify primary_key=True on any field of the model then Django will add a AutoField type field as the primary key .
  8. Field.unique : If True, the Field must have a unique value in the database table.
  9. Field.unique_for_month : Similar to unique_for_date, except that the Field is unique for the month.
  10. Field.validators : A list of validators that will be executed on this field.

4. Model MetaData.

Model metadata is “any data that is not a field”, such as ordering options, data table names (db_table), or human-readable singular and plural names (verbose_name and verbose_name_plural). You can use the internal class Meta to define the metadata for the model. Adding class Meta to the model is completely optional, none of the options are required.

from django.db import models
class test(models.Model):
   horn_length = models.IntegerField()
   
   class Meta:
      ordering = ["horn_length"]
      verbose_name_plural = "oxen"