django-4 field type data constraint table relation

Posted by teng84 on Sat, 21 Dec 2019 20:57:48 +0100

django

mysql

  1. model field type
   'AutoField': 'integer AUTO_INCREMENT',
           'BigAutoField': 'bigint AUTO_INCREMENT',
           'BinaryField': 'longblob',
           'BooleanField': 'bool',
           'CharField': 'varchar(%(max_length)s)',
           'CommaSeparatedIntegerField': 'varchar(%(max_length)s)',
           'DateField': 'date',
           'DateTimeField': 'datetime',
           'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)',
           'DurationField': 'bigint',
           'FileField': 'varchar(%(max_length)s)',
           'FilePathField': 'varchar(%(max_length)s)',
           'FloatField': 'double precision',
           'IntegerField': 'integer',
           'BigIntegerField': 'bigint',
           'IPAddressField': 'char(15)',
           'GenericIPAddressField': 'char(39)',
           'NullBooleanField': 'bool',
           'OneToOneField': 'integer',
           'PositiveIntegerField': 'integer UNSIGNED',
           'PositiveSmallIntegerField': 'smallint UNSIGNED',
           'SlugField': 'varchar(%(max_length)s)',
           'SmallIntegerField': 'smallint',
           'TextField': 'longtext',
           'TimeField': 'time',
           'UUIDField': 'char(32)',

DEMO:

from django.db import models

	# Create your models here.
	class userinfo(models.Model):
	    # id = models.IntegerField(primary_key=True)
	    id = models.AutoField(primary_key=True)

	    # Automatically create an id column with id as primary key and self growth
	    telephone = models.CharField(unique=True,max_length=11)
	    password = models.CharField(max_length=64)
	    email = models.EmailField(null=True,db_column='uemail')
	    regist_time=models.DateTimeField(auto_now_add=True,null=True)
	    # In order not to add an additional user type table, Admin can use the choices field
	    user_types=(
	        (1,'Ordinary users'),
	        (2,'VIP user'),
	        (3,'Administrators')
	    )

	    user_type_id=models.IntegerField(choices=user_types,default=1)
	    # memo = models.TextField()
  1. model data constraint
   null                Whether the field in the database can be empty
       db_column           Column name of the field in the database
           email = models.EmailField(null=True,db_column='uemail')
       db_tablespace
       default             Default values for fields in the database
       primary_key         Whether the fields in the database are primary keys
      		telephone = models.CharField(unique=True,max_length=30)
       db_index            Whether fields in the database can be indexed
       unique              Whether fields in the database can be uniquely indexed
       unique_for_date     Can a unique index be created for the date part of the field in the database
       unique_for_month    Can a unique index be created for the [month] part of the field in the database
       unique_for_year     Can a unique index be created for the year part of the field in the database
       auto_now_add			 This column automatically fills in the current system time
   ==
   Admin Fields used in the module
       verbose_name        Admin Field name shown in
       blank               Admin Allow user input to be blank in
       editable            Admin Whether it can be edited in
       help_text           Admin Prompt for this field in
       choices             Admin The contents of the selection box are displayed in, and unchanging data is placed in memory to avoid cross table operation
                           //For example: gf = models.IntegerField(choices=[(0, 'he Sui'), (1, 'big cousin'),], default=1)

       error_messages      Customize the error information (Dictionary type), so as to customize the error information to be displayed;
                           //Dictionary key: null, blank, invalid, invalid_choice, unique, and unique_for_date
                           //For example: {'null': "cannot be empty.", "invalid ':' format error '}

       validators          Customize error validation (list type) to customize the validation rules you want
                           from django.core.validators import RegexValidator
                           from django.core.validators import EmailValidator,URLValidator,DecimalValidator,\
                           MaxLengthValidator,MinLengthValidator,MaxValueValidator,MinValueValidator
                           //For example:
                               test = models.CharField(
                                   max_length=32,
                                   error_messages={
                                       'c1': 'Priority error message 1',
                                       'c2': 'Priority error message 2',
                                       'c3': 'Priority error message 3',
                                   },
                                   validators=[
                                       RegexValidator(regex='root_\d+', message='Wrong', code='c1'),
                                       RegexValidator(regex='root_112233\d+', message='Wrong again', code='c2'),
                                       EmailValidator(message='Wrong again', code='c3'), ]
                               )

DEMO:

       class UserInfo(models.Model):
           nid = models.AutoField(primary_key=True)
           username = models.CharField(max_length=32)
           class Meta:
               # Default app name + underline + class name of the generated table in the database
               db_table = "table_name"

               # Joint index
               index_together = [
                   ("pub_date", "deadline"),
               ]

               # Union unique index
               unique_together = (("driver", "restaurant"),)

               # Table name displayed in admin
               verbose_name

               # Verbose? Name plus s
               verbose_name_plural

        //More: https://docs.djangoproject.com/en/1.10/ref/models/options/
  1. Table relation
   1. Relationship
      -One to many: models.foreignkey (other tables)
      -Many to many: models.manytomanyfield (other tables)
      -One to one: models.onetoonefield (other tables)
   2. Set foreign key relationship (1:n)
      When the user type is saved to the database, django will automatically save the field as user type ID

          user_type=models.ForeignKey("usertype",to_field="id",default=1,on_delete= models.CASCADE)

   When the user type is saved to the database, django will automatically save the field as user type ID
   When querying user info table data, user type ID represents index value, and user type field can also be used. Its content is a type table object, so it can get name directly
       user = models.userinfo.objects.filter(telephone='root',password='999').first()

       if user:
           print(user.telephone)
           print(user.user_type_id)
           print(user.user_type.name)
   Note the addition of on_delete= models.CASCADE
   -models.CASCADE, delete the associated data, and delete the associated data
   -Models.do'noting, delete the associated data, and raise an integrity error
   -models.PROTECT, delete the associated data, raise the error ProtectedError
   -models.SET_NULL, delete the associated data, and set the associated value to null (if the FK field needs to be set to nullable)
   -Models.set? Default, delete the associated data, and set the associated value as the default value (if the FK field needs to set the default value)

Topics: Database Django MySQL