Fields of Django model layer operation

1. Field name naming restrictions

The Fields field is designated as a class attribute of the model class. It is the most important part of the model and the only necessary part of the model. It is used to define the database fields.

Django places some restrictions on field naming:

1. Pay attention to the field name and do not choose a name that conflicts with the model API, such as clean, save or delete, etc.

2. The field name cannot be a Python reserved word, because this will cause a Python syntax error. For example:

class Example(models.Model):
    pass = models.IntegerField() # 'pass'是保留字

3. Due to the way Django query syntax works, there cannot be more than two consecutive underscores in a field name. For example:

class Example(models.Model):
    foo__bar = models.IntegerField() # 错误,因字段'foo__bar'带有两个下划线

4. For similar reasons, field names cannot end with an underscore.

The above are only restrictions on model fields, not database columns. Our model field names do not match database column names. You can use the db_column field to specify the database name

class Example(models.Model):
    # 数据库中字段名改为aaa__aaa,但查询时仍用aaa
    aaa=models.CharField(max_length=10,db_column='aaa__aaa')  
    bbb=models.CharField(max_length=10,db_column='bbb_')

5. SQL reserved words such as select, where, and join can be used as the field name of the model, because Django will escape the database table name and column name in the underlying SQL query statement. It uses different quoting syntax depending on your database engine. Even if you can, we still don't recommend using reserved words.

2. Field type

#1、AutoField
int自增列,必须填入参数 primary_key=True。当model中如果没有自增列,则自动会创建一个列名为id的列。

#2、IntegerField
一个整数类型,范围在 -2147483648 to 2147483647。

#3、CharField
字符类型,必须提供max_length参数, max_length表示字符长度。

#4、DateField
日期字段,日期格式  YYYY-MM-DD,相当于Python中的datetime.date()实例。

#5、DateTimeField
日期时间字段,格式 YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ],相当于Python中的datetime.datetime()实例

example

from django.db import models

class Musician(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    instrument = models.CharField(max_length=100)

class Album(models.Model):
    artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)
    release_date = models.DateField()
    num_stars = models.IntegerField()

3. Field options/parameters

Each field has a set of parameters specific to that field. For example, the field CharField (and its subclasses) must define a max_length parameter, which specifies the size of the VARCHAR database field used to store data. For this part of parameters, refer to the official website or prompt to specify.

We mainly discuss the public parameters available for all field types, of course, all are optional

1. null:
If True, Django will store empty values ​​as NULL in the database. The default value is False.

2. blank:
If it is True, the field is allowed to be empty. The default value is False.

Note that this is not the same as null. null is purely database-related, while blank is validation-related. If the field has blank=True, the form validation will allow empty values ​​to be entered. The field is required if empty=false.

3、unique:

If True, the field must be unique

4、db_index

If db_index=True, it means setting an index for this field.

5、db_column

Specify the field name corresponding to the data
name = models.CharField(max_length=64, db_column='book_name')

The default field name is name. After specifying db_column, the database table field name is book_name

6、choices

Used to specify a two-tuple. If this option is given, the default form widget of the admin interface will be a selection box instead of a standard text field, and the selection will be limited to the given options, as follows

from django.db import models

class Person(models.Model):
    # 每个元组的第二个元素用来在amdin管理界面显示,而第一个元素才是被存入数据库中的值
    SHIRT_SIZES = (
        ('S', 'Small'),
        ('M', 'Medium'),
        ('L', 'Large'),
    )
    name = models.CharField(max_length=60)
    shirt_size = models.CharField(max_length=1, choices=SHIRT_SIZES)


>>> p = Person(name="Fred Flintstone", shirt_size="L")
>>> p.save()
>>> p.shirt_size
'L'
>>> p.get_shirt_size_display() # 可以使用get_FOO_display()方法访问具有选项的字段的显示值
'Large'

7.
The default value of the default field. This can be a value or a callable object. If callable, it will be called every time a new object is created.

from django.db import models

def func():
    print('from func')

class Person(models.Model):
    SHIRT_SIZES = (
        ('S', 'Small'),
        ('M', 'Medium'),
        ('L', 'Large'),
    )
    name = models.CharField(max_length=60,null=True,default=func)
    shirt_size = models.CharField(max_length=1, choices=SHIRT_SIZES)

# 首先我们设置null=True,default=函数
# 然后执行,当插入值为空时,会使用默认值,如果此时默认值为函数,则会触发函数的执行
>>> p = Person()
from func
>>> p.save()

8. auto_now_add

can set auto_now_add=True for DateField and DateTimeField, and the current time will be added automatically when adding new objects

create_time=models.DateTimeField(auto_now_add=True) # 只针对创建,不针对修改

9、auto_now

For DateField and DateTimeField, auto_now=True can be set, adding or modifying objects will automatically fill in the current time

modify_time=models.DateTimeField(auto_now=True) # 针对创建以及修改都有效

emphasize:

1 ), the options auto_now, auto_now_add and default are mutually exclusive. There can only be one.

2) There is a condition for the automatic update of auto_now=True, which is to pass through the model layer of django, so what operations are done through the model layer? ? ?

Such as create or save method, it is through the model layer

If it is the update method after the filter, the sql is called directly, and the model layer will not be passed, so the time will not be automatically updated. The official explanation is as follows

What you consider a bug, others may consider a feature,
 e.g. usingupdate_fieldsto bypass updating fields withauto_now. 
In fact, I wouldn't expectauto_nowfields to be updated 
if not present inupdate_fields.

Therefore, the way to make auto_now=True take effect is to manually pass in the time when changing to save() or update.

Summarize

auto_now_add=True
auto_now=True
二者的相同之处,在首次插入记录时,无论是使用create还save,都会自动填充时间
二者的不同之处在于,对于已经存在的记录,再进行update或者save操作时

auto_now_add=True(多用于记录数据的创建时间)
          无论是update还是.save()都不能更改他的值,所以其一般用于记录数据的创建时间

auto_now=True(多用于记录数据的更新时间)
          update方法不能改变其时间,除非updatet时自己手动传入时间才可以
          .save() 时auto_now能够自动填充时间
          例如:
          obj=Book.objects.filter(id=8).first()
    	  obj.title = "xxx"
    	  obj.save()  # auto_now的字段会自动更新时间

3 Pay attention to the time zone setting and modify the configuration file

TIME_ZONE = 'Asia/Shanghai'
USE_TZ = False  # 必须改为False

help_text, for additional "help" text displayed in the admin management interface. It is useful for documentation name = models.CharField(max_length=60,null=True,default=func,help_text='hahahahaha')

primary_key

If True, then this field is the primary key of the model.

Primary key fields are read-only. If you change the value of the primary key on an existing object and save it, it will not be modified, but a new object will be created. For example:

from django.db import models

class Fruit(models.Model):
    name = models.CharField(max_length=100, primary_key=True)
>>> fruit = Fruit.objects.create(name='Apple')
>>> fruit.name = 'Pear'
>>> fruit.save()
>>> Fruit.objects.values_list('name', flat=True)
<QuerySet ['Apple', 'Pear']>
如果你没有指定任何一个字段的primary_key=True,Django 就会自动添加一个IntegerField 字段做为主键,所以除非你想覆盖默认的主键行为,否则没必要设置任何一个字段的primary_key=True。 详见下一小节 四 自动主键字段
 默认情况下,django自动会为每个模型创建一个主键字段,这种自动的行为称之为隐式创建
id = models.AutoField(primary_key=True)

If you want to customize the primary key, you need to specify the parameter primary_key=True for one of your fields. This custom behavior is called explicit creation.
Django sees that you have customized the primary key, and it will not automatically create the id field.

4. Set the readme name of the field

With the exception of ForeignKey, ManyToManyField, and OneToOneField, each field type takes an optional first positional argument as verbose name. If no verbose name is specified to display, Django will automatically create it using the field's attribute name, converting underscores to spaces.

The detailed name displayed in the field of the admin management interface as follows: "person's first name"

first_name = models.CharField("person's first name", max_length=30)
# first_name = models.CharField(name="person's first name", max_length=30)

As follows, the detailed name displayed in the field is: "first name":

first_name = models.CharField(max_length=30)

For ForeignKey, ManyToManyField, and OneToOneField fields, the first parameter must be a model class. If you want to set the detailed name displayed by the field, you need to specify the parameter verbose_name, as follows

 

from django.db import models

class Person(models.Model):
    SHIRT_SIZES = (
        ('S', 'Small'),
        ('M', 'Medium'),
        ('L', 'Large'),
    )
    name = models.CharField('用户名',max_length=60,null=True,help_text='哈哈哈')
    role=models.ForeignKey(to='Role',verbose_name='权限选择',on_delete=models.CASCADE,null=True)

class Role(models.Model):
    PRIVS = (
        (0, 'superuser'),
        (1, 'user'),
        (2, 'visitor'),
    )

    role=models.CharField('角色',max_length=20)
    priv=models.IntegerField('权限',choices=PRIVS)

The convention is commonly known that the first letter of the detailed name will not be capitalized, and django will automatically capitalize the first letter where it is needed

5. Establish table relationship

It involves the use of fields ForeignKey, ManyToManyField, and OneToOneField, see the next section for details

Six, custom fields (understand)


Custom char type field:

class FixedCharField(models.Field):
    """
    自定义的char类型的字段类
    """
    def __init__(self, max_length, *args, **kwargs):
        self.max_length = max_length
        super(FixedCharField, self).__init__(max_length=max_length, *args, **kwargs)

    def db_type(self, connection):
        """
        限定生成数据库表的字段类型为char,长度为max_length指定的值
        """
        return 'char(%s)' % self.max_length


class Class(models.Model):
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=25)
    # 使用自定义的char类型的字段
    cname = FixedCharField(max_length=25)

Guess you like

Origin blog.csdn.net/weixin_47035302/article/details/131436660