Introduction to the Field type parameters and important Field parameters commonly used in Django ORM to create database and model

Creating a Django project and its application

django-admin startproject orm

cd orm

python manage.py startapp app01

Create database structure on models.py

from django.db import models

class Publisher(models.Model):
    name = models.CharField(max_length=30, verbose_name="Name")
    address = models.CharField("address", max_length=50)
    city = models.CharField("City", max_length=20)
    state_province = models.CharField(max_length=15)
    country = models.CharField(max_length=20)
    website = models.URLField()

    class Meta:
        verbose_name = 'Publisher'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name

class Author(models.Model):
    name = models.CharField(max_length=20)
    def __str__(self):
        return self.name


class AuthorDetail(models.Model):
    sex = models.BooleanField(max_length=1, choices=((0, 'male'),(1, 'female'),))
    email = models.EmailField()
    address = models.CharField(max_length=50)
    birthday = models.DateField()
    author = models.OneToOneField(Author,on_delete=models.CASCADE)

class Book(models.Model):
    title = models.CharField(max_length=100)
    authors = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher,on_delete=models.CASCADE)
    publication_date = models.DateField()
    price = models.DecimalField(max_digits=5, decimal_places=2, default=10)
    def __str__(self):
        return self.title

Add on settings.py

INSTALLED_APPS = [
 ......
 'app01',
]

Initialize database

# Use the command line to enter the project
# Generate script to synchronize database:
python manage.py makemigrations  

#Synchronize database:  
python manage.py migrate   

Common field type parameters of the model

 (1) CharField
        #String field for shorter strings
        #CharField requires a parameter maxlength to limit the maximum number of characters allowed for this field from the database layer and Django verification layer

(2) IntegerField
       #Used to hold an integer

(3) FloatField
        # A floating-point number. Two parameters must be provided:
        #
        # Parameter description
        # Max? Digits (excluding decimal point and symbol)
        # Decimal place
                # For example, to save a maximum value of 999 (2 decimal places), you define the fields as follows:
                #
                # models.FloatField(..., max_digits=5, decimal_places=2)
                # To save a maximum value of one million (10 decimal places), you need to define it as follows:
                #
                # models.FloatField(..., max_digits=19, decimal_places=10)
                # admin uses a text box (< input type = "text" >

(4) AutoField
        # An IntegerField that grows automatically when you add records. You usually don't need to use this field directly; 
        # Customize a primary key: my_id=models.AutoField(primary_key=True)
        # If you do not specify a primary key, the system will automatically add a primary key field to your model

(5) BooleanField
        # A true/false field. admin uses a checkbox to represent such fields

(6) TextField
        # A large text field
        # admin represents the field data with a < textarea > (a multiline edit box)

(7) EmailField
        # A CharField with check Email validity does not accept the maxlength parameter

(8) DateField
        # A date field. There are the following additional optional parameters:
        # Argument description
        # Auto now automatically sets the value of this field to the current time when the object is saved. It is usually used to represent the "last modified" timestamp
        # When an object is created for the first time, the value of this field is automatically set to the current time. It is usually used to represent the creation time of the object
        #(meaningful only in admin...)

(9) DateTimeField
        #  A date time field. Similar datefields support the same additional options

(10) ImageField
        # Similar FileField, However, check whether the uploaded object is a legal image.#It has two optional parameters: height field and width field,
        # If these two parameters are provided, the picture will be saved according to the height and width specifications provided     

(11) FileField
     # A file upload field
     #A required parameter is required: upload_to, A local file system path for saving uploaded files. This path must contain strftime #formatting, 
     #date/time of the file to be uploaded 
     #So that uploaded files don't fill up the given directory
     # admin uses a < input type = "file" > widget to represent the data saved in this field (a file upload widget)

     #Note: using FileField or ImageField in a model requires the following steps:
            #(1) in your settings file, define a full path to media? Root so that Django can save the uploaded file here 
            # (for performance reasons, these files are not saved to the database.) define the media u URL as the public URL of the directory. Make sure that the directory 
            #  The user account of WEB server is writable
            #(2) add FileField or ImageField to your model, and make sure the upload to option is defined to tell Django
            # Use which subdirectory of media root to save the uploaded file. All you need to save in your database is the path of the file (relative to media root) 
            # You must want to use it out of habit Django Provided get_<#For example, if your ImageField 
            # be known as mug_shot, You can use the {{ object.#Get the absolute path of the image

(12) URLField
      # It is used to save the URL. If the verify ﹣ exists parameter is True (default), the given URL will be pre checked for existence (i.e. whether the URL is effectively loaded and
      # No 404 response returned)
      # admin uses a < input type = "text" > text box to represent the data saved in this field (a single line edit box)

(13) NullBooleanField
       # Similar to the Boolean field, but NULL is allowed as one of the options. It is recommended to use this field instead of the Boolean field plus the null=True option
       # admin uses a selection box < Select > (three optional values: "Unknown", "Yes" and "No") to represent this field data

(14) SlugField
       # "Slug" It's a newspaper term. slug It's a little sign of something(Short signature), Letters only,number,Underscores and hyphens.#They are commonly used in URLs
       # If you use Django Development version,You can specify maxlength. if maxlength Not specified, Django Default length will be used: 50.  #stay
       # In the previous Django version, there was no way to change the length of 50
       # This implies db_index=True
       # It takes an extra parameter: prepopulate_from, which is a list of fields from which to auto-#populate 
       # the slug, via JavaScript,in the object's admin form: models.SlugField
       # (prepopulate from = ("pre name", "name")) prepopulate from does not accept DateTimeFields

(13) XMLField
        #Whether a check value is legal XML Of TextField,Parameters must be provided: schema_path, It is used to verify the text RelaxNG schema #File system path for

(14) FilePathField
        # The optional project is the file name in a specific directory. It supports three special parameters, the first of which must be provided
        # Parameter description
        # Path required parameter. The absolute file system path of a directory. FilePathField gets the optional item accordingly 
        # Example: "/home/images".
        # match optional parameter. A regular expression, as a string, FilePathField will use it to filter filenames  
        # Note that this regular expression only applies to base filename instead of
        # Full path name. Example: "foo.*\.txt ^", will match file foo23.txt but not bar.txt or foo23.gif
        # recursive optional parameter. Either True or False. The default value is False. Include all subdirectories under path
        # These three parameters can be used at the same time
        # match only applies to the base filename, not the full path name. Then, this example:
        # FilePathField(path="/home/images", match="foo.*", recursive=True)
        # ... will match / home/images/foo.gif and not / home/images/foo/bar.gif

(15) IPAddressField
        # An IP address in the form of a string, (i.e. "24.124.1.30")

(16)  CommaSeparatedIntegerField
        # Used to store comma separated integer values. Similar to CharField, maxlength parameter is required

Field important parameters

(1) null: whether the field in the database can be empty

(2) can null values be allowed when adding data to the Admin of blank: django

(3) default: set the default value

(4) edit table: if it is false, it cannot be overwritten in admin mode. Default is true

(5) primary_key: set the primary key. If django is not set to create a table, it will be added automatically:
        id = meta.AutoField('ID', primary_key=True)
        primary_key=True implies blank=False, null=False and unique=True. Only one
        primary key is allowed on an object.

(6) unique: unique data

(7) verbose [u name: display name of the field in Admin

(8) validator list: validity check. Invalid django.core.validators.ValidationError

(9) DB column, DB index: if true, index will be created for this field

(10)choices: a two-dimensional tuple used to select values. The first value is the actual stored value, and the second is used to facilitate selection.
          For example, SEX_CHOICES = ('F', 'Female'), ('M ',' Male '),)
          gender = models.CharField(max_length=2,choices = SEX_CHOICES)

Tags: Python Django Database Web Server

Posted on Fri, 08 Nov 2019 12:12:38 -0800 by eulalyn09