Django中的Model字段
字段选项
这里的选项,适用于所有的字段类型,且都是可选的null # 如果设置为 True, 当该字段为空时,Django 会将数据库中该字段设置为 NULL,默认为 False blank # 如果设置为 True ,该字段允许为空。默认为 False 。 choices # 用于提供选项,如果设置了此参数,则在ModelForm的widget不是使用了text输入框,而是select标签 # choices的例子 gender_choices = ((1, '男'), (2, '女')) gender = models.SmallIntegerField(verbose_name='性别', choices=gender_choices) # choices结束 # 使用选项的另一种方式 class Card(models.Model): class Suit(models.IntegerChoices): DIAMOND = 1 SPADE = 2 HEART = 3 CLUB = 4 suit = models.IntegerField(choices=Suit.choices) db_column # 在数据库中生成的字段名 db_index # 如果设为True,则此字段为索引 db_tablespace # 不清楚 default # 该字段的默认值。可以是一个值或者是个可调用的对象,如果是个可调用对象,每次实例化模型时都会调用该对象。 editable # 默认为True,如果为False,则在admin或ModelForm中不显示,同时也会跳过验证 error_messages # 自定义错误信息 help_text # 额外的“帮助”文本,随表单控件一同显示。即便你的字段未用于表单,它对于生成文档也是很有用的。 primary_key # True则表明是主键 unique # 如果设置为 True,这个字段必须在整个表中保持值唯一。 unique_for_date # 此字段要与设置的DateField或者DateTimeField字段联合唯一,如下: title = models.CharField(max_length=32, unique_for_date='pub_date') pub_date = models.DateField() unique_for_month # 类似以上 unique_for_year # 类似以上 verbose_name # 方便阅读的名称 validators # 自定义验证规则,可参考https://docs.djangoproject.com/en/3.0/ref/validators/
字段中的特殊选项
不同类型的字段也有其特殊的选项,不适合于其它字段的
BinaryField
二进制类型字段 BinaryField.max_lengthCharField
字符串型字段 CharField.max_lengthDateField、TimeField
DateField.auto_now:每次调用obj.save时更新修改时间,用QuerySet方法没效 DateField.auto_now_add:保存创建时间DecimalField
带有小数的数值 DecimalField.max_digits:最大的位数 DecimalField.decimal_places:小数点位数FileField
FileField.upload_to# 例一 class MyModel(models.Model): # file will be uploaded to MEDIA_ROOT/uploads upload = models.FileField(upload_to='uploads/') # or... # file will be saved to MEDIA_ROOT/uploads/2015/01/30 upload = models.FileField(upload_to='uploads/%Y/%m/%d/') # 例二 def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_/ return 'user_{0}/{1}'.format(instance.user.id, filename) class MyModel(models.Model): upload = models.FileField(upload_to=user_directory_path)
如何使用FileField字段,如下:
from django.db import models class Car(models.Model): name = models.CharField(max_length=255) price = models.DecimalField(max_digits=5, decimal_places=2) photo = models.ImageField(upload_to='cars') from django.core.files import File # Create a Python file object using open() f = open('/path/to/hello.world', 'w') myfile = File(f) car1.photo = myfile myfile.close() # 文件相关操作 car1.photo.name car1.photo.size car1.photo.url car1.photo.path car1.photo.open(mode='rb') car1.photo.close() car1.photo.save(name, content, save=True) car1.photo.delete(save=True)
FilePathField
这其实是一个带有choices属性的CharField,有以下参数 path:必选,是一个路径,可调用一个方法生成 match:正则表达式,匹配的是文件名,不匹配路径 recursive:包括路径中的子目录 allow_files:允许文件 allow_folders:允许目录ImageField
有FileField的所有属性,依赖于pillow,参数如下: height_field,width_field:保存高度、宽度的字符串名称GenericIPAddressField
参数: protol:both、IPV4、IPV6 unpack_ipv4:IPV4 IPV6映射,需要protocal为bothUUIDField
可代替AutoField(primary_key=True)id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)ForeignKey
多对一的外键约束,有以下参数: to:关联表(必须) on_delete:关联数据被删除行为 (必须),有以下,都在模块django.db.models下 CASCADE:同时删除 PROTECT:保护数据 SET_NULL:关联数据设为空,注意要配置null=True使用 SET_DEFAULT:设默认值 SET():设为指定的值,参数可为一个可调用的函数 DO_NOTHING:什么都不做 limit_choices_to:用于ModelForm或者admin,用于限制选择的条件,可为Q对象或{字段:值}或一个可调用函数 related_name:反查,一般先获取obj,然后obj.定义的related_name.all() related_query_name:也是反查,一般用于filter# models class Book(models.Model): title = models.CharField(max_length=32) author = models.ForeignKey(to='Author', on_delete=models.CASCADE, related_name='author_field', related_query_name='author_tab') class Author(models.Model): name = models.CharField(max_length=32) # views # 查询 pk=1出版的书 author = models.Author.objects.get(pk=1) print(author.author_field.all()) # 查询出版python基础的作者 print(models.Author.objects.filter(author_tab__title='Python基础')) return HttpResponse('...')to_field:关联的字段,需要设此字段为unique=True
db_constrains:设为False则不外键约束,但一般不会这样做
swappable:一般不会改ManyToManyField
ForeignKey中的参数都具有,还有以下参数 through:第三张表类的名称 through_fields:关联的字段from django.db import models class Person(models.Model): name = models.CharField(max_length=50) class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField( Person, through='Membership', through_fields=('group', 'person'), ) class Membership(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE) inviter = models.ForeignKey( Person, on_delete=models.CASCADE, related_name="membership_invites", ) invite_reason = models.CharField(max_length=64)db_table:在数据库中创建的第三张表名称
symmetrical:默认为True,一般用在关联的是自己表格的时候OneToOneField
参数: parent_link:沿不明白其它字段
AutoField BigAutoField BigIntegerField BooleanField DurationField EmailField IntegerField NullBooleanField PositiveIntegerField PostiveSmallField SlugField:只有字母、数字、下划线、连接符,一般用于URL,参数:allow_unicode SmallAutoField SmallIntegerField Textfield