Home >Backend Development >Python Tutorial >Django documentation - Model field types (FieldTypes)
Field types (Field types)
AutoField
It is an IntegerField field that grows automatically based on ID. Normally, you don't have to use this field directly. If you don't specify a primary key on another field, Django The primary key field will be added automatically.
BigIntegerField
64-bit integer, similar to IntegerField, ranging from -9223372036854775808 To 9223372036854775807. The default form widget is TextInput.
BooleanField
A Boolean value (true/false) field.
The default form widget is CheckboxInput.
If you want to use null as the empty value, you can use NullBooleanField.
CharField
class CharField(max_length=None[, **options])
It is a string field, suitable for both small and large strings.
For larger text, TextField should be used.
The default form widget is TextInput.
CharField has a parameter that must be passed in: max_length, the maximum number of characters in the field. It works at both the database level and Django's data validation level.
CommaSeparatedInterField
class CommaSeparatedIntegerField(max_length=None[, **options])
It is used to store a comma-separated sequence of integers. Like CharField, it must be provided with the max_length parameter. Also note that different databases have different max_length limits.
DateField
class DateField([auto_now=False, auto_now_add=False, **options])
This field uses Python’s datetime.date instance to represent the date. Here are its additional optional parameters:
DateField.auto_now: Every time the object is saved, Django will automatically set the value of this field to the current time. Generally used to mean "last modified" time. Please note that the current date is used, not the default value, so
cannot change the save time by overwriting the default value.
DateField.auto_now_add: When the object is first created, Django Automatically sets the value of this field to the current time, which is generally used to represent the object creation time. It also uses the current date instead of the default value.
The default form widget is TextInput.
Note: When auto_now or auto_now_add is set to True, the field will have editable=True and blank=True settings.
DateTimeField
class DateTimeField([auto_now=False, auto_now_add=False, **options])
This field uses datetime.datetime instances to represent date and time. This field accepts the same parameters as DateField.
The default form widget is TextInput. Django's admin uses two TextInputs with javaScript shortcut options to represent date and time respectively.
DecimalField
class DecimalField(max_digits=None, decimal_places=None[, **options])
It is a field that uses a Decimal instance to represent a fixed-precision decimal number. It has two required parameters:
DecimalField.max_digits: the maximum number of digits allowed for a number
DecimalField.decimal_places: the maximum number of digits for a decimal
For example, the maximum number to be stored is 999, and with two decimals digits, you can use:
models.DecimalField(..., max_digits=5, decimal_places=2)
To store numbers that are roughly in the billions with 10 decimal places, just write:
models.DecimalField(..., max_digits=19, decimal_places=10)
The default form widget is TextInput.
EmailField
class EmailField([max_length=75, **options])
It is a CharField with email legality detection.
Note: The maximum length defaults to 75 and cannot store all email addresses compatible with RFC3696/5321. If you want to store them all, set
max_length=254. Setting it to 75 is a legacy issue.
FileField
class FileField(upload_to=None[, max_length=100, **options])
File upload field
Note: This field does not support PRimary_key and unique parameters, otherwise a TypeError will be thrown abnormal.
It has one required parameter:
FileField.upload_to
The local file system used to save the file. It determines the url attribute of the file based on the MEDIA_ROOT setting.
The path can contain the time format string strftime(), which can be replaced with the current date/time when uploading files (in this way, a directory will not be filled up when uploading files).
This parameter can also be a callable item, such as a function. You can call the function to obtain the upload path containing the file name. This callable must accept two arguments,
, and return a Unix-Style path (with / slashes) to save the file. The two parameters are:
instance: defines the model instance of the current FileField. More precisely, it is the model instance with that file as an attachment.
Most of the time, when saving this file, model The instance object has not been saved to the database yet, because it is most likely using the default AutoField, and it has not yet obtained the primary key value from the database.
filename: the original name of the uploaded file. It may be used when generating the final path.
There is also an optional parameter:
FileField.storage
The object responsible for saving and obtaining files.
The default form widget is FileInput.
Note: To use FileField or ImageField in model, follow the following steps:
1. In the project settings file, you need to define MEDIA_ROOT and set its value to the full path of the directory used to store uploaded files. (Based on performance considerations, Django does not save files in the database).
Then define MEDIA_URL and set its value to the URL representing the directory.
Make sure that the account used by the web server has write permissions to the directory.
2. Add FileField or ImageField in the model, and confirm that the upload_to item has been defined to let Django Know which subdirectory of
MEDIA_ROOT should be used to save files.
3. What is stored in the database is only the path of the file (and it is a relative path relative to MEDIA_ROOT). You may have thought of taking advantage of the convenient url attribute provided by
Django. For example, if your ImageField name is mug_shot, then you can use
{{ object.mug_shot.url }}
in the template
to get the full URL of the image.
For example, assuming your MEDIA_ROOT is set to '/home/media' and upload_to is set to 'photos/%Y/%m/%d'. '%Y/%m/%d' in upload_to is a strftime(), '%Y' is a four-digit year, '%m' is a two-digit month, '%d' is a two-digit day . If you
uploaded a file on January 15, 2007, then the file will be saved in the /home/media/photos/2007/01/15 directory.
If you want to get the local file name, file URL, or file size of the uploaded file, you can use the name, url and size attributes.
Note: When uploading files, be careful about the location and type of files you save. The reason for doing this is to avoid security vulnerabilities. Verify every uploaded
file so you can make sure the file you upload is the one you want. For example, if you blindly let others upload files without
verifying the uploaded files, if the directory where the files are saved is in the root directory of the web server, if someone uploads a CGI or php
script, Then running the uploaded script by accessing the script URL is too dangerous. Don't let this happen!
By default, the corresponding column of the FileField instance in the database is varchar(100). Like other fields, you can use max_length Parameter changes the maximum length of the field.
FileField and FieldFile
class FieldFile
When you access the FileField
field of a Model, you will get an instance of FieldFile as a proxy to access the underlying file. Instances have several properties and methods that can be used to interact with file data.
FieldFile.url
Call the url() method of the underlying storage class in a read-only manner to access the relative URL of the file.
FieldFile.open(mode='rb')
Similar to python's open() method.
FieldFile.close()
Similar to python’s close() method.
FieldFile.save(name,content,save=True)
This method passes the filename and file content to the field and then stores it to the model. This method requires two necessary parameters: name, the name of the file, content, An object containing the contents of a file. The save parameter is optional and mainly controls whether the instance is saved after the file is modified. The default is True . It should be noted that the content parameter is django.core.files.File An instance of , which is not Python's built-in File object. You can use
to build a file from an existing Python file object as follows:
from django.core.files import File
# Open an existing file using Python's built-in open()f = open('/tmp/hello.world')
myfile = File(f)
or construct from string:
from django.core.files.base import ContentFile
FieldFile.delete(save=True)
Deletes the file related to this instance and clears all attributes of the field.
Note: When delete() is called, if the file happens to be open, this method will close the file. The
save parameter is optional and controls whether the instance is saved after the file is deleted. The default is True .
It should be noted that when a model is deleted, the related files are not deleted. If you want to delete these orphan files, you need to handle it yourself (for example, you can manually run the cleanup command, or you can regularly execute the cleanup command through cron)
FilePathField
class FilePathField(path=None[, match=None, recursive= False, max_length=100, **options])
It is a CharField, which is used to select certain files in a directory under the file system. It has three proprietary parameters, only the first parameter
is required:
FilePathField.path
This parameter is required. It is the absolute path to the directory that the FilePathField uses to select the file. For example: "/home/images".
FilePathField.match
Optional parameters. It is a regular expression string that FilePathField uses to filter file names. Only files that meet the criteria appear in the
file selection list. Note that the regular expression only matches file names, not file paths. For example: "foo.*.txt$" only matches files named
foo23.txt but does not match bar.txt and foo23.gif.
FilePathField.recursive
Optional parameter. Its value is True or False. The default value is False. It specifies whether to include subdirectories under path.
FilePathField.allow_files
This item is a new addition to Django 1.5. Optional parameter whose value is True or False. The default value is True. It specifies whether to include the file at the specified location. One of this item and allow_folders must be True.
FilePathField.allow_folders
New in Django 1.5. Optional parameter, its value is True or False. The default is False. It specifies whether to include the directory at the specified location. One of this item and allow_files must be True.
As mentioned earlier, match only matches file names, not file paths. So the following example:
FilePathField(path="/home/images", match="foo.*", recursive=True)
will match /home/images/foo.gif, not /home/ images/foo/bar.gif. This is because match only matches filenames
(foo.gif and bar.gif).
By default, the corresponding column of the FilePathField instance in the database is varchar(100). Like other fields, you can use max_length Parameter changes the maximum length of the field.
FloatField
class FloatField([**options])
This field uses a float instance in Python to represent a floating point number.
The default form widget is TextInput.
Please note the difference between FloatField and DecimalField.
ImageField
class ImageField(upload_to=None[, height_field=None, width_field=None, max_length=100,**options])
Same as FileField, except that it will verify whether the uploaded object is a legal image file.
In addition to the parameters valid in FileField, ImageField can also use the two properties File.height and File.width .
It has two optional parameters:
ImageField.height_field
The name of the field that saves the height of the image. When saving the object, the image file will be scaled and converted based on the height set in this field.
ImageField.width_field
The name of the field that saves the width of the image. When saving the object, the image file will be scaled and converted according to the width set in this field.
By default, the ImageField instance corresponds to varchar(100) in the database List. Like other fields, you can change the maximum length of the field using the max_length parameter.
IntegerField
class IntegerField([**options])
Integer field. The default form widget is TextInput.
IPAddressField
class IPAddressField([**options])
Represents the IP address field in string form (such as "192.0.2.30"). The default form widget is TextInput.
GenericIPAddressField
class GenericIPAddressField([**options])
New in Django1.4.
Represents the IP4 or IP6 address field in string form (such as "192.0.2.30" or "2a02:42fe::4"). Default form The widget is TextInput.
IPv6 address format follows RFC 4291 section 2.2. For example, if this address is actually an IPv4 address, the last 32 bits can be represented by decimal numbers, such as "::ffff:192.0.2.0".
2001:0::0:01 can be written as 2001::1, and ::ffff:0a0a:0a0a can be written as::ffff:10.10.10.10. Letters are all lowercase.
GenericIPAddressField.protocol
Verify the validity of the input protocol. The default value is ‘both’ which is IPv4 or IPv6. This entry is not case sensitive.
GenericIPAddressField.unpack_ipv4
Explains the IPv4 mapped address, like ::ffff:192.0.2.1 . If this option is enabled, the address will be interpreted as 192.0.2.1 . The default is disabled. only if Can only be enabled if protocol is set to 'both'.
NullBooleanField
class NullBooleanField([**options])
Similar to BooleanField, but with an additional NULL option. It is recommended to use this field instead of a BooleanField using the null=True option.
The default form widget is NullBooleanSelect.
PositiveIntegerField
class PositiveIntegerField([**options])
Similar to IntegerField, but the field value must be a non-negative number.
PositiveSmallIntegerField
class PositiveSmallIntegerField([**options])
is similar to PositiveIntegerField, but the value range is smaller and limited by database settings.
SlugField
class SlugField([max_length=50, **options])
Slug is a news term that refers to a short label for an event. It can only consist of letters, numbers, underscores or hyphens. In general, it is used as part of the URL.
Similar to CharField, you can specify max_length (pay attention to database compatibility and max_length mentioned in this section). if not specified max_length, Django will default the field length to 50.
This field automatically sets Field.db_index to True.
It is useful to automatically populate the Slug field based on the value of other fields. You can use prepopulated_fields in Django's admin to do this.
SmallIntegerField
class SmallIntegerField([**options])
is similar to IntegerField, but the value range is smaller and is limited by database limitations.
TextField
class TextField([**options])
Large text field. The default form widget is Textarea.
TimeField
class TimeField([auto_now=False, auto_now_add=False, **options])
This field uses Python’s datetime.time instance to represent time. It accepts the same autocomplete parameters as DateField.
The default form widget is TextInput.
URLField
class URLField([max_length=200, **options])
CharField that saves the URL.
Like all CharField subclasses, URLField accepts an optional max_length parameter, whose default value is 200.
The above is the content of the Django document - Model Field Types (FieldTypes). For more related articles, please pay attention to the PHP Chinese website (www.php.cn)!