Home >Backend Development >Python Tutorial >Django documentation - Model field options (FieldOptions)

Django documentation - Model field options (FieldOptions)

黄舟
黄舟Original
2016-12-17 16:08:001291browse

Create a simple Model

class Person(models.Model):
GENDER_CHOICES=(
(1,'Male'),
(2,'Female'),
)
name=models.CharField(max_length= 30, unique=True,verbose_name='name')
birthday=models.DateField(blank=True,null=True)
gender=models.IntegerField(choices=GENDER_CHOICES)
account=models.IntegerField(default=0)

blank

When set to True, the field can be empty. When set to False, the field is required. Character fields CharField and TextField use empty strings to store null values.

null

When set to True, django uses Null to store empty values. Date, time, and numeric fields do not accept empty strings. Therefore, when setting IntegerField and DateTimeField fields to be empty, you need to set blank and null to True.

If you want to set the BooleanField to be empty, you can choose the NullBooleanField type field.

max_length

Set the maximum length for CharField type fields.

choices

choices consists of a sequence of 2-tuples (list or tuple) as the field. The first element of the 2-tuple is stored in the database, and the second element can be obtained by the get_FOO_display method.

>>>p=Person(name='Sam',gender=1)
>>>p.save()
>>>p.gender
1
>> ;>p.get_gender_display()
u'Male'

If there are too many options, it is best to consider using ForiegnKey.

default

Set a default value for a field.

The default value cannot be a mutable object (model instance, list, collection, etc.), as a reference to the same instance, the object will be used as the default value in all new model instances. Instead, encapsulate the desired default values ​​in a callable object. For example, if you have a custom JSONField and want to specify one as the default dictionary, use a lambda expression as follows:

contact_info = JSONField("ContactInfo", default=lambda:{"email": "to1@example. com"})

verbose_name

Set the display name of this field on the admin interface.

unique

Set to True, this field must be unique in the database.

>>>p=Person(name='Sam',gender=1)
>>>p.save()
>>>p=Person(name='Sam' ,gender=2)
>>>p.save()
IntergrityError: column name is not unique

PRimary_key

If set to True, this field becomes the primary key of the Model. Under normal circumstances, django will automatically add an IntegerField called id as the primary key to the Model.

The above is the content of the Django document - Model Field Options (FieldOptions). For more related articles, please pay attention to the PHP Chinese website (www.php.cn)


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn