#字段选项
null 如果是 True, Django 将在数据库中存储空值为 NULL。默认为 False。 blank 如果是 True ,该字段允许为空。默认为 False 。 choices from django.db import models class Student(models.Model): FRESHMAN = 'FR' SOPHOMORE = 'SO' JUNIOR = 'JR' SENIOR = 'SR' GRADUATE = 'GR' YEAR_IN_SCHOOL_CHOICES = [ (FRESHMAN, 'Freshman'), (SOPHOMORE, 'Sophomore'), (JUNIOR, 'Junior'), (SENIOR, 'Senior'), (GRADUATE, 'Graduate'), ] year_in_school = models.CharField( max_length=2, choices=YEAR_IN_SCHOOL_CHOICES, default=FRESHMAN, ) #枚举类型---TextChoices rom django.utils.translation import gettext_lazy as _ class Student(models.Model): class YearInSchool(models.TextChoices): FRESHMAN = 'FR', _('Freshman') SOPHOMORE = 'SO', _('Sophomore') JUNIOR = 'JR', _('Junior') SENIOR = 'SR', _('Senior') GRADUATE = 'GR', _('Graduate') year_in_school = models.CharField( max_length=2, choices=YearInSchool.choices, default=YearInSchool.FRESHMAN, ) #枚举类型---IntegerChoices class Card(models.Model): class Suit(models.IntegerChoices): DIAMOND = 1 SPADE = 2 HEART = 3 CLUB = 4 suit = models.IntegerField(choices=Suit.choices) default 该字段的默认值 primary_key 如果设置为 True ,将该字段设置为该模型的主键。如果你没有为模型中的任何字段指定 primary_key=True,Django 会自动添加一个字段来保存主键 unique 如果设置为 True,这个字段必须在整个表中保持值唯一。 verbose_name 字段的一个人类可读名称
#字段类型
AutoField() ID 自动递增。 BigAutoField() 与 AutoField 很相似, 1 ~ 9223372036854775807 SmallAutoField() 与 AutoField 很相似, 1 ~ 32767 IntegerField() 整型,范围 -2147483648 ~ 2147483647 BigIntegerField() 整型,范围 -9223372036854775808 ~ 9223372036854775807 SmallIntegerField() 整型,范围 -32768 ~ 32767 PositiveIntegerField() 整型,范围 0 ~ 2147483647 PositiveBigIntegerField() 整型,范围 0 ~ 9223372036854775807 PositiveSmallIntegerField() 整型,范围 0~ 32767 BooleanField() 布尔值 FloatField() 浮点型 DecimalField(max_digits=None, decimal_places=None) 固定精度的十进制数 max_digits,小数总长度 decimal_places,小数位长度 CharField(max_length=None) 字符字段,必须提供max_length参数 TextField() 文本字段 EmailField(max_length=254) 电子邮件地址 GenericIPAddressField(protocol=’both’, unpack_ipv4=False) IPv4 或 IPv6 地址,字符串格式(如 192.0.2.30 或 2a02:42fe::4 )。 protocol,将有效输入限制为指定协议。接受的值是 'both' (默认)、'IPv4' 或 'IPv6'。 unpack_ipv4,解压 IPv4 映射地址,只有当 protocol 设置为 'both' 时才会启用。 URLField(max_length=200) URL SlugField(max_length=50) 字符串字段,支持 字母、数字、下划线、连接符(减号) UUIDField() 通用唯一标识符 FilePathField(path='', match=None, recursive=False, allow_files=True, allow_folders=False, max_length=100) 选择文件系统中某个目录下的文件名 path, 文件夹路径 match=None, 正则匹配 recursive=False, 递归子文件夹 allow_files=True, 允许文件 allow_folders=False, 允许文件夹 FileField(upload_to=None, max_length=100) 文件上传 upload_to = "" 上传文件的保存路径 'uploads/'或者'uploads/%Y/%m/%d/' storage = None 存储组件 ImageField(upload_to=None, height_field=None, width_field=None, max_length=100,) 字符串字段,路径保存在数据库,文件上传到指定目录 width_field=None, 模型字段的名称,每次保存模型实例时将自动填充图像的宽度。 height_field=None 模型字段的名称,每次保存模型实例时将自动填充图像的高度。 DateTimeField(auto_now=False, auto_now_add=False) 日期时间格式 YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] auto_now,每次保存对象时,自动将该字段设置为现在。对于“最后修改”的时间戳很有用。 auto_now_add,当第一次创建对象时,自动将该字段设置为现在。对创建时间戳很有用。 DateField(auto_now=False, auto_now_add=False) 日期格式 YYYY-MM-DD TimeField(auto_now=False, auto_now_add=False) 时间格式 HH:MM[:ss[.uuuuuu]] DurationField() 用于存储时间段 数据库中按照bigint存储,ORM中获取的值为datetime.timedelta字段 BinaryField(max_length=None,) 二进制字段 JSONField(encoder=None, decoder=None) 存储 JSON 编码数据 encoder,用于序列化标准 JSON 序列化器不支持的数据字段(例如 datetime.datetime 或 UUID ) decoder,用于反序列化从数据库中获取的值
#关系字段
#ForeignKey 多对一的关系 from django.db import models class Car(models.Model): manufacturer = models.ForeignKey( 'Manufacturer', on_delete=models.CASCADE, ) # ... class Manufacturer(models.Model): # ... pass #ManyToManyField 多对多的关系 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)
#创建表
from django.db import models class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() def __str__(self): return self.name class Author(models.Model): name = models.CharField(max_length=200) email = models.EmailField() def __str__(self): return self.name class Entry(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) headline = models.CharField(max_length=255) body_text = models.TextField() pub_date = models.DateField() mod_date = models.DateField() authors = models.ManyToManyField(Author) number_of_comments = models.IntegerField() number_of_pingbacks = models.IntegerField() rating = models.IntegerField() def __str__(self): return self.headline
#字段查询
基本的查询关键字参数遵照 field__lookuptype=value
Entry.objects.filter(pub_date__lte='2006-01-01') # WHERE pub_date <= '2006-01-01' ntry.objects.get(headline__exact="Cat bites dog") # WHERE headline = 'Cat bites dog' Entry.objects.get(headline="Cat bites dog") # WHERE headline = 'Cat bites dog' Blog.objects.get(name__iexact="beatles blog") # 不分大小写的匹配 Entry.objects.get(headline__contains='Lennon') # WHERE headline LIKE '%Lennon%'; Entry.objects.filter(id__in=[1, 3, 4]) # WHERE id IN (1, 3, 4); Entry.objects.filter(headline__in='abc') # WHERE headline IN ('a', 'b', 'c'); Entry.objects.filter(id__gt=4) # WHERE id > 4; Entry.objects.filter(headline__startswith='Lennon') # WHERE headline LIKE 'Lennon%'; Entry.objects.filter(headline__endswith='Lennon') # WHERE headline LIKE '%Lennon'; Entry.objects.filter(pub_date__range=(datetime.date(2005, 1, 1), datetime.date(2005, 3, 31))) # WHERE pub_date BETWEEN '2005-01-01' and '2005-03-31'; Entry.objects.filter(pub_date__year__gte=2005) # WHERE pub_date >= '2005-01-01'; Entry.objects.filter(pub_date__month=12) # 对于日期和日期时间字段,精确的月份匹配 Entry.objects.filter(pub_date__day=3) # 对于日期和日期时间字段,精确匹配日期 Entry.objects.filter(pub_date__week=52) # 对于日期和日期时间字段,返回星期号 Entry.objects.filter(pub_date__week_day=2) # 对于日期和日期时间字段,“星期几”匹配 Entry.objects.filter(pub_date__isnull=True) # WHERE pub_date IS NULL;
# 查询
#创建对象 from blog.models import Blog b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.') b.save() #将修改保存至对象 from blog.models import Blog, Entry,Author entry = Entry.objects.get(pk=1) entry.number_of_comments=5 cheese_blog = Blog.objects.get(name="Cheddar Talk") entry.blog = cheese_blog entry.save() joe = Author.objects.create(name="Joe") george = Author.objects.create(name="George") entry.authors.add(joe,george) #检索对象 all_entries = Entry.objects.all() #全部对象 Entry.objects.filter(pub_date__year=2006) Entry.objects.filter(headline__startswith='What').exclude(pub_date__gte=datetime.date.today()).filter(pub_date__gte=datetime.date(2005, 1, 30)) one_entry = Entry.objects.get(pk=1) #单个对象 Entry.objects.all()[5:10] #第 6 至第 10 个对象
#跨关系查询
Entry.objects.filter(blog__name='Beatles Blog') #检索出所有的 Entry 对象,其 Blog 的 name 为 'Beatles Blog' Blog.objects.filter(entry__headline__contains='Lennon') # 检索的所有 Blog 对象均拥有少一个 标题 含有 'Lennon' 的条目
标签:__,models,max,django,objects,date,Entry From: https://www.cnblogs.com/caroline2016/p/16913429.html