Model基础

一、连接mysql

    1.打开project/__init__.py,输入如下内容:

import pymysql
pymysql.install_as_MySQLdb()

   2.修改settings文件中的mysql相关配置,如下:

 

二、字段:

一)常用字段

AutoField(Field)
        - int自增列,必须填入参数 primary_key=True

    BigAutoField(AutoField)
        - bigint自增列,必须填入参数 primary_key=True

        注:当model中如果没有自增列,则自动会创建一个列名为id的列
        from django.db import models

        class UserInfo(models.Model):
            # 自动创建一个列名为id的且为自增的整数列
            username = models.CharField(max_length=32)

        class Group(models.Model):
            # 自定义自增列
            nid = models.AutoField(primary_key=True)
            name = models.CharField(max_length=32)

    SmallIntegerField(IntegerField):
        - 小整数 -3276832767

    PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField)
        - 正小整数 032767
    IntegerField(Field)
        - 整数列(有符号的) -21474836482147483647

    PositiveIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField)
        - 正整数 02147483647

    BigIntegerField(IntegerField):
        - 长整型(有符号的) -92233720368547758089223372036854775807

    BooleanField(Field)
        - 布尔值类型

    NullBooleanField(Field):
        - 可以为空的布尔值

    CharField(Field)
        - 字符类型
        - 必须提供max_length参数, max_length表示字符长度

    TextField(Field)
        - 文本类型

    EmailField(CharField):
        - 字符串类型,Django Admin以及ModelForm中提供验证机制

    IPAddressField(Field)
        - 字符串类型,Django Admin以及ModelForm中提供验证 IPV4 机制

    GenericIPAddressField(Field)
        - 字符串类型,Django Admin以及ModelForm中提供验证 Ipv4和Ipv6
        - 参数:
            protocol,用于指定Ipv4或Ipv6, 'both',"ipv4","ipv6"
            unpack_ipv4, 如果指定为True,则输入::ffff:192.0.2.1时候,可解析为192.0.2.1,开启刺功能,需要protocol="both"

    URLField(CharField)
        - 字符串类型,Django Admin以及ModelForm中提供验证 URL

    SlugField(CharField)
        - 字符串类型,Django Admin以及ModelForm中提供验证支持 字母、数字、下划线、连接符(减号)

    CommaSeparatedIntegerField(CharField)
        - 字符串类型,格式必须为逗号分割的数字

    UUIDField(Field)
        - 字符串类型,Django Admin以及ModelForm中提供对UUID格式的验证

    FilePathField(Field)
        - 字符串,Django Admin以及ModelForm中提供读取文件夹下文件的功能
        - 参数:
                path,                      文件夹路径
                match=None,                正则匹配
                recursive=False,           递归下面的文件夹
                allow_files=True,          允许文件
                allow_folders=False,       允许文件夹

    FileField(Field)
        - 字符串,路径保存在数据库,文件上传到指定目录
        - 参数:
            upload_to = ""      上传文件的保存路径
            storage = None      存储组件,默认django.core.files.storage.FileSystemStorage

    ImageField(FileField)
        - 字符串,路径保存在数据库,文件上传到指定目录
        - 参数:
            upload_to = ""      上传文件的保存路径
            storage = None      存储组件,默认django.core.files.storage.FileSystemStorage
            width_field=None,   上传图片的高度保存的数据库字段名(字符串)
            height_field=None   上传图片的宽度保存的数据库字段名(字符串)

    DateTimeField(DateField)
        - 日期+时间格式 YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]

    DateField(DateTimeCheckMixin, Field)
        - 日期格式      YYYY-MM-DD

    TimeField(DateTimeCheckMixin, Field)
        - 时间格式      HH:MM[:ss[.uuuuuu]]

    DurationField(Field)
        - 长整数,时间间隔,数据库中按照bigint存储,ORM中获取的值为datetime.timedelta类型

    FloatField(Field)
        - 浮点型

    DecimalField(Field)
        - 10进制小数
        - 参数:
            max_digits,小数总长度
            decimal_places,小数位长度

    BinaryField(Field)
        - 二进制类型

字段列表

二)自定义无符号证书字段

class UnsignedIntegerField(models.IntegerField):
    def db_type(self, connection):
        return 'integer UNSIGNED'

PS: 返回值为字段在数据库中的属性,Django字段默认的值为:
    'AutoField': 'integer AUTO_INCREMENT',
    'BigAutoField': 'bigint AUTO_INCREMENT',
    'BinaryField': 'longblob',
    'BooleanField': 'bool',
    'CharField': 'varchar(%(max_length)s)',
    'CommaSeparatedIntegerField': 'varchar(%(max_length)s)',
    'DateField': 'date',
    'DateTimeField': 'datetime',
    'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)',
    'DurationField': 'bigint',
    'FileField': 'varchar(%(max_length)s)',
    'FilePathField': 'varchar(%(max_length)s)',
    'FloatField': 'double precision',
    'IntegerField': 'integer',
    'BigIntegerField': 'bigint',
    'IPAddressField': 'char(15)',
    'GenericIPAddressField': 'char(39)',
    'NullBooleanField': 'bool',
    'OneToOneField': 'integer',
    'PositiveIntegerField': 'integer UNSIGNED',
    'PositiveSmallIntegerField': 'smallint UNSIGNED',
    'SlugField': 'varchar(%(max_length)s)',
    'SmallIntegerField': 'smallint',
    'TextField': 'longtext',
    'TimeField': 'time',
    'UUIDField': 'char(32)',

自定义无符号整数字段

三)字段参数:

null                数据库中字段是否可以为空
    db_column           数据库中字段的列名
    default             数据库中字段的默认值
    primary_key         数据库中字段是否为主键
    db_index            数据库中字段是否可以建立索引
    unique              数据库中字段是否可以建立唯一索引
    unique_for_date     数据库中字段【日期】部分是否可以建立唯一索引
    unique_for_month    数据库中字段【月】部分是否可以建立唯一索引
    unique_for_year     数据库中字段【年】部分是否可以建立唯一索引

    verbose_name        Admin中显示的字段名称
    blank               Admin中是否允许用户输入为空
    editable            Admin中是否可以编辑
    help_text           Admin中该字段的提示信息
    choices             Admin中显示选择框的内容,用不变动的数据放在内存中从而避免跨表操作
                        如:gf = models.IntegerField(choices=[(0, '何穗'),(1, '大表姐'),],default=1)

    error_messages      自定义错误信息(字典类型),从而定制想要显示的错误信息;
                        字典健:null, blank, invalid, invalid_choice, unique, and unique_for_date
                        如:{'null': "不能为空.", 'invalid': '格式错误'}

    validators          自定义错误验证(列表类型),从而定制想要的验证规则
                        from django.core.validators import RegexValidator
                        from django.core.validators import EmailValidator,URLValidator,DecimalValidator,\
                        MaxLengthValidator,MinLengthValidator,MaxValueValidator,MinValueValidator
                        如:
                            test = models.CharField(
                                max_length=32,
                                error_messages={
                                    'c1': '优先错信息1',
                                    'c2': '优先错信息2',
                                    'c3': '优先错信息3',
                                },
                                validators=[
                                    RegexValidator(regex='root_\d+', message='错误了', code='c1'),
                                    RegexValidator(regex='root_112233\d+', message='又错误了', code='c2'),
                                    EmailValidator(message='又错误了', code='c3'), ]
                            )

三、元信息

https://docs.djangoproject.com/en/1.11/ref/models/options/

class UserInfo(models.Model):
        nid = models.AutoField(primary_key=True)
        username = models.CharField(max_length=32)
        class Meta:
            # 数据库中生成的表名称 默认 app名称 + 下划线 + 类名
            db_table = "table_name"

            # 联合索引
            index_together = [
                ("pub_date", "deadline"),
            ]

            # 联合唯一索引
            unique_together = (("driver", "restaurant"),)

            # admin中显示的表名称
            verbose_name

            # verbose_name加s
            verbose_name_plural

 

四、单表数据库的添、删、改、查

1.创建数据库:
    1).
     a.
     models.UserInfo.objects.create(username='123',password='123')   
     b.
    dic={'username':'eric','password':'666'}
    models.UserInfo.objects.create(**dic)
    

     2).
     obj = models.UserInfo(username='abc',password='123')
     obj.save()

2.查看数据:
      1).
      models.UserInfo.objects.all()
      #返回结果为 QuerySet类型,Dango提供的一种类型,此类型为一个列表[],列表中为对象,每个对象为表中的行
      #<QuerySet [<UserInfo: UserInfo object>, <UserInfo: UserInfo object>, <UserInfo: UserInfo object>]>
     查询内容
    # res = models.UserInfo.objects.all()
    # for r in res:
    #     print (r.id,r.username,r.password)
    #
     2).

     models.UserInfo.objects.filter(username='root')
     #返回结果同上:
     #<QuerySet [<UserInfo: UserInfo object>, <UserInfo: UserInfo object>]>

    查询内容:
     同上:
3).
modles.UserInfo.objects.filter(id__gt=1,name='root') #gt,lt gte lte
dic = {'name':'xxx','age__gt':19}
models.UserInfo.objects.filter(**dic)

v= models.UserInfo.objects.all() #此查询及上面的filter查询均返回QuerySet,内部元素均为对象。
前台调用方法:
      {% for row in  v %} #调用返回值为字典的元素
<li>{{ row.id }} -{{ row.username }}- {{ row.password }} </li>
{% endfor %}


4).
v = modles.UserInfo.objects.all().values('id','usernmae','password') #后跟查询字段名,返回值仍未QuerySet类型(列表),但内部则为字典形式,如下:
#<QuerySet [{'id': 1, 'password': '1111', 'username': 'root'}, {'id': 2, 'password': '2222', 'username': 'zhangsan'}, {'id': 3, 'password': '3333', 'username': 'lisi'}]>
前台调用方法:
{% for row in v %} #调用返回值为字典的元素
<li>{{ row.id }} -{{ row.username }}- {{ row.password }} </li>
{% endfor %}


5).
vl = models.UserInfo.objects.all().values_list('id','username','password') #后跟出啊讯字段名,返回值仍未QuerySet类型(列表),但内部元素为元祖,如下:
#<QuerySet [(1, 'root', '1111'), (2, 'zhangsan', '2222'), (3, 'lisi', '3333')]>
前台调用方法:
{% for row in vl %}
<li> {{ row.0 }} -{{ row.1}} - {{ row.2 }}
{% endfor %}

6).
v = models.UserInfo.objects.get(id=1) #获取的不在是QuerySet,而是一个具体的对象,如果不存在(id=1)的元素,则直接报错,抛出异常。
#可以用下面的方法解决:
v = models.UserInfo.objects.filter(id=1).first() #获取的为对象,如果没有(id=1)的元素,则返回None
3.删除 models.UserInfo.objects.filter(id='3').delete() 4.更新 models.UserInfo.objects.all(password='111') #所有用户密码给位111 models.UserInfo.objects.filter(username='root',password='111').update(password='222')

四)更多ORM操作

1.进阶操作

# 获取个数
        #
        # models.Tb1.objects.filter(name='seven').count()

        # 大于,小于
        #
        # models.Tb1.objects.filter(id__gt=1)              # 获取id大于1的值
        # models.Tb1.objects.filter(id__gte=1)              # 获取id大于等于1的值
        # models.Tb1.objects.filter(id__lt=10)             # 获取id小于10的值
        # models.Tb1.objects.filter(id__lte=10)             # 获取id小于10的值
        # models.Tb1.objects.filter(id__lt=10, id__gt=1)   # 获取id大于1 且 小于10的值

        # in
        #
        # models.Tb1.objects.filter(id__in=[11, 22, 33])   # 获取id等于11、22、33的数据
        # models.Tb1.objects.exclude(id__in=[11, 22, 33])  # not in

        # isnull
        # Entry.objects.filter(pub_date__isnull=True)

        # contains
        #
        # models.Tb1.objects.filter(name__contains="ven")
        # models.Tb1.objects.filter(name__icontains="ven") # icontains大小写不敏感
        # models.Tb1.objects.exclude(name__icontains="ven")

        # range
        #
        # models.Tb1.objects.filter(id__range=[1, 2])   # 范围bettwen and

        # 其他类似
        #
        # startswith,istartswith, endswith, iendswith,

        # order by
        #
        # models.Tb1.objects.filter(name='seven').order_by('id')    # asc
        # models.Tb1.objects.filter(name='seven').order_by('-id')   # desc

        # group by
        #
        # from django.db.models import Count, Min, Max, Sum
        # models.Tb1.objects.filter(c1=1).values('id').annotate(c=Count('num'))   annotate根据values值进行分组 c=Count('num')计算每个分组元素个数
        # SELECT "app01_tb1"."id", COUNT("app01_tb1"."num") AS "c" FROM "app01_tb1" WHERE "app01_tb1"."c1" = 1 GROUP BY "app01_tb1"."id"

        # limit 、offset
        #
        # models.Tb1.objects.all()[10:20]

        # regex正则匹配,iregex 不区分大小写
        #
        # Entry.objects.get(title__regex=r'^(An?|The) +')
        # Entry.objects.get(title__iregex=r'^(an?|the) +')

        # date
        #
        # Entry.objects.filter(pub_date__date=datetime.date(2005, 1, 1))
        # Entry.objects.filter(pub_date__date__gt=datetime.date(2005, 1, 1))

        # year
        #
        # Entry.objects.filter(pub_date__year=2005)
        # Entry.objects.filter(pub_date__year__gte=2005)

        # month
        #
        # Entry.objects.filter(pub_date__month=12)
        # Entry.objects.filter(pub_date__month__gte=6)

        # day
        #
        # Entry.objects.filter(pub_date__day=3)
        # Entry.objects.filter(pub_date__day__gte=3)

        # week_day
        #
        # Entry.objects.filter(pub_date__week_day=2)
        # Entry.objects.filter(pub_date__week_day__gte=2)

        # hour
        #
        # Event.objects.filter(timestamp__hour=23)
        # Event.objects.filter(time__hour=5)
        # Event.objects.filter(timestamp__hour__gte=12)

        # minute
        #
        # Event.objects.filter(timestamp__minute=29)
        # Event.objects.filter(time__minute=46)
        # Event.objects.filter(timestamp__minute__gte=29)

        # second
        #
        # Event.objects.filter(timestamp__second=31)
        # Event.objects.filter(time__second=2)
        # Event.objects.filter(timestamp__second__gte=31)


2.高级操作

  # extra
        #
        # extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None)
        #    Entry.objects.extra(select={'new_id': "select col from sometable where othercol > %s"}, select_params=(1,))
        #    Entry.objects.extra(where=['headline=%s'], params=['Lennon'])
        #    Entry.objects.extra(where=["foo='a' OR bar = 'a'", "baz = 'a'"])
        #    Entry.objects.extra(select={'new_id': "select id from tb where id > %s"}, select_params=(1,), order_by=['-nid'])

        # F
        #
        # from django.db.models import F
        # models.Tb1.objects.update(num=F('num')+1)


        # Q
        #
        # 方式一:
        # Q(nid__gt=10)
        # Q(nid=8) | Q(nid__gt=10)
        # Q(Q(nid=8) | Q(nid__gt=10)) & Q(caption='root')

        # 方式二:
        # con = Q()
        # q1 = Q()
        # q1.connector = 'OR'
        # q1.children.append(('id', 1))
        # q1.children.append(('id', 10))
        # q1.children.append(('id', 9))
        # q2 = Q()
        # q2.connector = 'OR'
        # q2.children.append(('c1', 1))
        # q2.children.append(('c1', 10))
        # q2.children.append(('c1', 9))
        # con.add(q1, 'AND')
        # con.add(q2, 'AND')
        #
        # models.Tb1.objects.filter(con)


        # 执行原生SQL
        #
        # from django.db import connection, connections
        # cursor = connection.cursor()  # cursor = connections['default'].cursor()
        # cursor.execute("""SELECT * from auth_user where id = %s""", [1])
        # row = cursor.fetchone()

3.其它操作

##################################################################
# PUBLIC METHODS THAT ALTER ATTRIBUTES AND RETURN A NEW QUERYSET #
##################################################################

def all(self)
    # 获取所有的数据对象

def filter(self, *args, **kwargs)
    # 条件查询
    # 条件可以是:参数,字典,Q

def exclude(self, *args, **kwargs)
    # 条件查询
    # 条件可以是:参数,字典,Q

def select_related(self, *fields)
     性能相关:表之间进行join连表操作,一次性获取关联的数据。
     model.tb.objects.all().select_related()
     model.tb.objects.all().select_related('外键字段')
     model.tb.objects.all().select_related('外键字段__外键字段')

def prefetch_related(self, *lookups)
    性能相关:多表连表操作时速度会慢,使用其执行多次SQL查询在Python代码中实现连表操作。
            # 获取所有用户表
            # 获取用户类型表where id in (用户表中的查到的所有用户ID)
            models.UserInfo.objects.prefetch_related('外键字段')



            from django.db.models import Count, Case, When, IntegerField
            Article.objects.annotate(
                numviews=Count(Case(
                    When(readership__what_time__lt=treshold, then=1),
                    output_field=CharField(),
                ))
            )

            students = Student.objects.all().annotate(num_excused_absences=models.Sum(
                models.Case(
                    models.When(absence__type='Excused', then=1),
                default=0,
                output_field=models.IntegerField()
            )))

def annotate(self, *args, **kwargs)
    # 用于实现聚合group by查询

    from django.db.models import Count, Avg, Max, Min, Sum

    v = models.UserInfo.objects.values('u_id').annotate(uid=Count('u_id'))
    # SELECT u_id, COUNT(ui) AS `uid` FROM UserInfo GROUP BY u_id

    v = models.UserInfo.objects.values('u_id').annotate(uid=Count('u_id')).filter(uid__gt=1)
    # SELECT u_id, COUNT(ui_id) AS `uid` FROM UserInfo GROUP BY u_id having count(u_id) > 1

    v = models.UserInfo.objects.values('u_id').annotate(uid=Count('u_id',distinct=True)).filter(uid__gt=1)
    # SELECT u_id, COUNT( DISTINCT ui_id) AS `uid` FROM UserInfo GROUP BY u_id having count(u_id) > 1

def distinct(self, *field_names)
    # 用于distinct去重
    models.UserInfo.objects.values('nid').distinct()
    # select distinct nid from userinfo

    注:只有在PostgreSQL中才能使用distinct进行去重

def order_by(self, *field_names)
    # 用于排序
    models.UserInfo.objects.all().order_by('-id','age')

def extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None)
    # 构造额外的查询条件或者映射,如:子查询

    Entry.objects.extra(select={'new_id': "select col from sometable where othercol > %s"}, select_params=(1,))
    Entry.objects.extra(where=['headline=%s'], params=['Lennon'])
    Entry.objects.extra(where=["foo='a' OR bar = 'a'", "baz = 'a'"])
    Entry.objects.extra(select={'new_id': "select id from tb where id > %s"}, select_params=(1,), order_by=['-nid'])

 def reverse(self):
    # 倒序
    models.UserInfo.objects.all().order_by('-nid').reverse()
    # 注:如果存在order_by,reverse则是倒序,如果多个排序则一一倒序


 def defer(self, *fields):
    models.UserInfo.objects.defer('username','id')
    或
    models.UserInfo.objects.filter(...).defer('username','id')
    #映射中排除某列数据

 def only(self, *fields):
    #仅取某个表中的数据
     models.UserInfo.objects.only('username','id')
     或
     models.UserInfo.objects.filter(...).only('username','id')

 def using(self, alias):
     指定使用的数据库,参数为别名(setting中的设置)


##################################################
# PUBLIC METHODS THAT RETURN A QUERYSET SUBCLASS #
##################################################

def raw(self, raw_query, params=None, translations=None, using=None):
    # 执行原生SQL
    models.UserInfo.objects.raw('select * from userinfo')

    # 如果SQL是其他表时,必须将名字设置为当前UserInfo对象的主键列名
    models.UserInfo.objects.raw('select id as nid from 其他表')

    # 为原生SQL设置参数
    models.UserInfo.objects.raw('select id as nid from userinfo where nid>%s', params=[12,])

    # 将获取的到列名转换为指定列名
    name_map = {'first': 'first_name', 'last': 'last_name', 'bd': 'birth_date', 'pk': 'id'}
    Person.objects.raw('SELECT * FROM some_other_table', translations=name_map)

    # 指定数据库
    models.UserInfo.objects.raw('select * from userinfo', using="default")

    ################### 原生SQL ###################
    from django.db import connection, connections
    cursor = connection.cursor()  # cursor = connections['default'].cursor()
    cursor.execute("""SELECT * from auth_user where id = %s""", [1])
    row = cursor.fetchone() # fetchall()/fetchmany(..)


def values(self, *fields):
    # 获取每行数据为字典格式

def values_list(self, *fields, **kwargs):
    # 获取每行数据为元祖

def dates(self, field_name, kind, order='ASC'):
    # 根据时间进行某一部分进行去重查找并截取指定内容
    # kind只能是:"year"(年), "month"(年-月), "day"(年-月-日)
    # order只能是:"ASC"  "DESC"
    # 并获取转换后的时间
        - year : 年-01-01
        - month: 年-月-01
        - day  : 年-月-日

    models.DatePlus.objects.dates('ctime','day','DESC')

def datetimes(self, field_name, kind, order='ASC', tzinfo=None):
    # 根据时间进行某一部分进行去重查找并截取指定内容,将时间转换为指定时区时间
    # kind只能是 "year", "month", "day", "hour", "minute", "second"
    # order只能是:"ASC"  "DESC"
    # tzinfo时区对象
    models.DDD.objects.datetimes('ctime','hour',tzinfo=pytz.UTC)
    models.DDD.objects.datetimes('ctime','hour',tzinfo=pytz.timezone('Asia/Shanghai'))

    """
    pip3 install pytz
    import pytz
    pytz.all_timezones
    pytz.timezone(‘Asia/Shanghai’)
    """

def none(self):
    # 空QuerySet对象


####################################
# METHODS THAT DO DATABASE QUERIES #
####################################

def aggregate(self, *args, **kwargs):
   # 聚合函数,获取字典类型聚合结果
   from django.db.models import Count, Avg, Max, Min, Sum
   result = models.UserInfo.objects.aggregate(k=Count('u_id', distinct=True), n=Count('nid'))
   ===> {'k': 3, 'n': 4}

def count(self):
   # 获取个数

def get(self, *args, **kwargs):
   # 获取单个对象

def create(self, **kwargs):
   # 创建对象

def bulk_create(self, objs, batch_size=None):
    # 批量插入
    # batch_size表示一次插入的个数
    objs = [
        models.DDD(name='r11'),
        models.DDD(name='r22')
    ]
    models.DDD.objects.bulk_create(objs, 10)

def get_or_create(self, defaults=None, **kwargs):
    # 如果存在,则获取,否则,创建
    # defaults 指定创建时,其他字段的值
    obj, created = models.UserInfo.objects.get_or_create(username='root1', defaults={'email': '1111111','u_id': 2, 't_id': 2})

def update_or_create(self, defaults=None, **kwargs):
    # 如果存在,则更新,否则,创建
    # defaults 指定创建时或更新时的其他字段
    obj, created = models.UserInfo.objects.update_or_create(username='root1', defaults={'email': '1111111','u_id': 2, 't_id': 1})

def first(self):
   # 获取第一个

def last(self):
   # 获取最后一个

def in_bulk(self, id_list=None):
   # 根据主键ID进行查找
   id_list = [11,21,31]
   models.DDD.objects.in_bulk(id_list)

def delete(self):
   # 删除

def update(self, **kwargs):
    # 更新

def exists(self):
   # 是否有结果

其他操作

 

三、多表操作

一)一对多跨表查询(外键关联)

1.正向查找:

1.views.py
#1.当QuerySet中元素内容为对象时的取值方法
    #hosts = models.Host.objects.all()
    #for row in hosts:
        # print (row.nid,row.hostname,row.ip,row.port,row.b_id,row.b)
        #输入结果:
        # 1 c1 1.1.1.1 80 1 Business object
        # 2 c2 1.1.1.2 8080 Business object
        #print(row.nid, row.hostname, row.ip, row.port, row.b_id, row.b.id,row.b.caption,row.b.code)
        #1 c1 1.1.1.1 80 1 1 研发 1
        #2 c2 1.1.1.2 8080 1 1 研发 1
        #3 c3 2.2.2.3 90 2 2 运维 2
   前端取值方法:
    {% for row in v1 %}
            <tr hid="{{ row.nid }}" bid="{{ row.b_id }}">
                <td>{{ row.hostname }}</td>
                <td>{{ row.ip }}</td>
                <td>{{ row.port }}</td>
                <td>{{ row.b_id }}</td>
                <td>{{ row.b.caption }}</td>
                <td>{{ row.b.code }}</td>
            </tr>
        {% endfor %}
    #2.当QuerySet中元素内容为字典的取值方法(values)
    v2 =     models.Host.objects.filter(nid__gt=0).values('nid','hostname','b_id','b__caption')
    for row in v2:
        print(row['nid'],row['hostname'],row['b_id'],row['b__caption'])

前端取值方法:
   {% for row in v2 %}
          <tr hid="{{ row.nid}}" bid="{{ row.b_id }}">
                  <td>{{ row.hostname }}</td>
                  <td>{{ row.b__capiton }} </td>
          </tr>
   {% endfor %}
   #3.当QuerySet中元素内容为元祖的取值方法(values_list)
   v3 = models.Host.objects.filter(nid__gt=0).values_list('nid','hostname','b_id','b__caption')
    for row in v3:
         print (row[0],row[1],row[2],row[3])

前端取值方法:
   <tbody >
        {% for row in v1 %}
            <tr hid="{{ row.0 }}">
                <td>{{ row.1 }}</td>
                <td>{{ row.2 }}</td>
                <td>{{ row.3 }}</td>
            </tr>
        {% endfor %}
    </tbody>

<td>{{ forloop.counter }}</td>
<td>{{ forloop.counter0 }}</td>
<td>{{ forloop.revcounter }} </td>
<td>{{ forloop.revcounter0 }} </td>
<td>{{ forloop.last }}</td> 是否是最后一个循环,是,返回True,否,返回False
<td>{{ forloop.parenloop }} </td>

2.反向查找:

1.models.py
class UserType(models.Model)
     name = models.CharField(max_length=32)

class User(models.Model):
     user = models.CharField(max_length=32)
     pwd = models.CharField(max_length=32)
     ut = models.CharField(to="UserType",to_field='id')

#v = User.objects.all()
#for item in v:
#       item.user
#       item.pwd
#       item.ut.name   <-----正向查找
#models.UserType.objects.all().values('name','user__pwd') <------正向查找

#User.objects.all().values(
'user','ut__name') <-------正向查找 #v = UserType.objects.all() #for item in v: # item.name # item.id # item.user_set.all() <------反向查找

自定制反向查找
1.related_name
class User(models.Model): user = models.CharField(max_length=32) pwd = models.CharField(max_length=32) ut = models.CharField(to="UserType",to_field='id',related_name='b')

#v = UserType.objects.all()
#for item in v:
#       item.name
#       item.id
#       item.user_set.all()  改为  ----> item.b.all()
2.related_query_name
class User(models.Model):
     user = models.CharField(max_length=32)
     pwd = models.CharField(max_length=32)
     ut = models.CharField(to="UserType",to_field='id',related_query_name='a')

#v = UserType.objects.all()
#for item in v:
#       item.name
#       item.id
#       item.user_set.all()  改为  ----> item.a_set.all()

 

 二)一对多插入数据

1.新URL方法插入数据

1.views.py
def host(request):
    if request.method == "GET":
    #1.当QuerySet中元素内容为对象时的取值方法
        v1 = models.Host.objects.filter(nid__gt=0)
        v2 = models.Host.objects.filter(nid__gt=0).values('nid','hostname','b_id','b__caption')
        v3 = models.Host.objects.filter(nid__gt=0).values_list('nid','hostname','b_id','b__caption')
        b_list = models.Business.objects.all()
        return render(request,'hosts.html',{'v1':v1,'v2':v2,'v3':v3,'b_list':b_list})
    elif request.method == "POST":
        h = request.POST.get('hostname')
        i = request.POST.get('ip')
        p = request.POST.get('port')
        b = request.POST.get('b_id')
        print("b=",b)

        models.Host.objects.create(
            hostname = h,
            ip = i,
            port = p,
            b_id = b
        )
    return redirect('/host/')

2.models.py
from django.db import models



class Business(models.Model):
    caption = models.CharField(max_length=32)
    code = models.CharField(max_length=32,null=True,default='SA')


class Host(models.Model):
    nid = models.AutoField(primary_key=True)
    hostname = models.CharField(max_length=32,db_index=True)
    ip = models.GenericIPAddressField(protocol='ipv4',db_index=True)
    port = models.IntegerField()
    b = models.ForeignKey(to="Business",to_field='id')
3.host.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .hide{
            display:none;
        }
        .shade{
            position:fixed;
            top:0;
            right:0;
            left:0;
            bottom:0;
            background:black;
            opacity:0.6;
            z-index:100;
        }
        .add-modal {
            position:fixed;
            height:300px;
            width:400px;
            top:100px;
            left:50%;
            z-index:101;
            border:1px solid red;
        }
        .add-
    </style>
</head>
<body >
<div>
    <input id="add_host" type="button" value="添加" />
</div>
<table border="1">
    <thead>
        <tr>
            <th>主机名</th>
            <th>IP</th>
            <th>端口</th>
            <th>业务线ID</th>
            <th>业务线名称</th>
            <th>业务线编码</th>

        </tr>
    </thead>
    <tbody >
        {% for row in v1 %}
            <tr hid="{{ row.hostname }}">
                <td>{{ row.ip }}</td>
                <td>{{ row.port }}</td>
                <td>{{ row.b.caption}}</td>
            </tr>
        {% endfor %}
    </tbody>
    </table>
    <div class="shade hide">ddd</div>
    <div class="add-modal hide">
        <form  method="POST" action="">
        <div class="group">
            <input type="text" placeholder="主机名" name="hostname" />
        </div>
        <div class="group">
            <input type="text" placeholder="IP" name="ip" />
        </div>
        <div class="group">
            <input type="text" placeholder="端口" name="port" />
        </div>
        <div class="group" >
            <select name="b_id">
                {% for op in b_list %}
                    <option value="{{ op.id }}">{{ op.caption }}</option>

                {% endfor %}
            </select>
        </div>
        <input type="submit" value="提交">
        <input type="button" value="取消">
        </form>
    </div>
    <script src="/static/jquery.min.js"></script>
    <script>
        $(function(){
            $(function(){
                $('#add_host').click(function(){
                    $('.shade,.add-modal').removeClass('hide');
                })
            })
        })
    </script>
</body>
</html>
4.urls.py
from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^host/',views.host),
]

 2.ajax方法插入数据:

1.views.py
def test_ajax(request):
    h = request.POST.get('hostname')
    i = request.POST.get('ip')
    p = request.POST.get('port')
    b = request.POST.get('b_id')
    if h and len(h) > 5:

        models.Host.objects.create(
            hostname = h,
            ip = i,
            port = p,
            b_id = b
        )
        return HttpResponse('ok')
    else:
        return HttpResponse('主机名太短了')
2.host.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .hide{
            display:none;
        }
        .shade{
            position:fixed;
            top:0;
            right:0;
            left:0;
            bottom:0;
            background:black;
            opacity:0.6;
            z-index:100;
        }
        .add-modal {
            position:fixed;
            height:300px;
            width:400px;
            top:100px;
            left:50%;
            z-index:101;
            border:1px solid red;
        }
        .add-
    </style>
</head>
<body >
<div>
    <input id="add_host" type="button" value="添加" />
</div>
<table border="1">
    <thead>
        <tr>
            <th>主机名</th>
            <th>IP</th>
            <th>端口</th>
            <th>业务线ID</th>
            <th>业务线名称</th>
            <th>业务线编码</th>

        </tr>
    </thead>
    <tbody >
        {% for row in v1 %}
            <tr hid="{{ row.hostname }}">
                <td>{{ row.ip }}</td>
                <td>{{ row.port }}</td>
                <td>{{ row.b.caption}}</td>

            </tr>
        {% endfor %}
    </tbody>
    </table>
    <div class="shade hide">ddd</div>
    <div class="add-modal hide">
        <form  method="POST" action="">
        <div class="group">
            <input id='host' type="text" placeholder="主机名" name="hostname" />
        </div>
        <div class="group">
            <input id="ip" type="text" placeholder="IP" name="ip" />
        </div>
        <div class="group">
            <input id="port" type="text" placeholder="端口" name="port" />
        </div>
        <div class="group" >
            <select id="sel" name="b_id">
                {% for op in b_list %}
                    <option value="{{ op.id }}">{{ op.caption }}</option>

                {% endfor %}
            </select>
        </div>
        <input type="submit" value="提交">
        <a id="ajax_submit" style="dispaly:none-block;background:blue;color:white">悄悄提交</a>
        <input id='cancel' type="button" value="取消">
        </form>
    </div>
    <script src="/static/jquery.min.js"></script>
    <script>
        $(function(){
            $(function(){
                $('#add_host').click(function(){
                    $('.shade,.add-modal').removeClass('hide');
                });
                $('#cancel').click(function(){
                    $('.shade,.add-modal').addClass('hide');
                });
                $('#ajax_submit').click(function(){
                    $.ajax({
                        url:"/test_ajax/",
                        type:"POST",
                        data:{'hostname':$('#host').val(),'ip':$('#ip').val(),'port':$('#port').val(),'b_id':$('#sel').val()},
                        success:function(data){
                            if(data="OK"){
                                location.reload()
                            }else{
                                alert(data);
                            }
                        }
                    })
                })
            })
        })
    </script>
</body>
</html>
3.modles.py
from django.db import models



class Business(models.Model):
    caption = models.CharField(max_length=32)
    code = models.CharField(max_length=32,null=True,default='SA')


class Host(models.Model):
    nid = models.AutoField(primary_key=True)
    hostname = models.CharField(max_length=32,db_index=True)
    ip = models.GenericIPAddressField(protocol='ipv4',db_index=True)
    port = models.IntegerField()
    b = models.ForeignKey(to="Business",to_field='id')
4.urls.py
from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^host/',views.host),
    url(r'^test_ajax/',views.test_ajax),
]

3.ajax与后台的交互

1.views.py
def test_ajax(request):
    import json
    ret = {'status':True,'error':None,'data':None}
    try:
        h = request.POST.get('hostname')
        i = request.POST.get('ip')
        p = request.POST.get('port')
        b = request.POST.get('b_id')
        if h and len(h) > 5:

            models.Host.objects.create(
                hostname = h,
                ip = i,
                port = p,
                b_id = b
            )
            return HttpResponse('ok')
        else:
            ret['status'] = False
            ret['error'] = '太短了'
    except Exception as e:
        ret['status'] = False
        ret['error'] = '请求错误'

    return HttpResponse(json.dumps(ret))   #字段转化成字符串

2.hosts.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .hide{
            display:none;
        }
        .shade{
            position:fixed;
            top:0;
            right:0;
            left:0;
            bottom:0;
            background:black;
            opacity:0.6;
            z-index:100;
        }
        .add-modal {
            position:fixed;
            height:300px;
            width:400px;
            top:100px;
            left:50%;
            z-index:101;
            border:1px solid red;
        }
        .add-
    </style>
</head>
<body >
<div>
    <input id="add_host" type="button" value="添加" />
</div>
<table border="1">
    <thead>
        <tr>
            <th>主机名</th>
            <th>IP</th>
            <th>端口</th>
            <th>业务线ID</th>
            <th>业务线名称</th>
            <th>业务线编码</th>

        </tr>
    </thead>
    <tbody >
        {% for row in v1 %}
            <tr hid="{{ row.hostname }}">
                <td>{{ row.ip }}</td>
                <td>{{ row.port }}</td>
                <td>{{ row.b.caption}}</td>

            </tr>
        {% endfor %}
    </tbody>
    </table>
    <div class="shade hide">ddd</div>
    <div class="add-modal hide">
        <form  method="POST" action="">
        <div class="group">
            <input id='host' type="text" placeholder="主机名" name="hostname" />
        </div>
        <div class="group">
            <input id="ip" type="text" placeholder="IP" name="ip" />
        </div>
        <div class="group">
            <input id="port" type="text" placeholder="端口" name="port" />
        </div>
        <div class="group" >
            <select id="sel" name="b_id">
                {% for op in b_list %}
                    <option value="{{ op.id }}">{{ op.caption }}</option>

                {% endfor %}
            </select>
        </div>
        <input type="submit" value="提交">
        <a id="ajax_submit" style="dispaly:none-block;background:blue;color:white">悄悄提交</a>
        <input id='cancel' type="button" value="取消">
        <span id="error_msg"></span>
        </form>
    </div>
    <script src="/static/jquery.min.js"></script>
    <script>
        $(function(){
            $(function(){
                $('#add_host').click(function(){
                    $('.shade,.add-modal').removeClass('hide');
                });
                $('#cancel').click(function(){
                    $('.shade,.add-modal').addClass('hide');
                });
                $('#ajax_submit').click(function(){
                    $.ajax({
                        url:"/test_ajax/",
                        type:"POST",
                        data:{'hostname':$('#host').val(),'ip':$('#ip').val(),'port':$('#port').val(),'b_id':$('#sel').val()},
                        success:function(data){
                            //data是服务器端返回的字符串
                            var obj = JSON.parse(data);   //字符串转化成对象
                                       //JSON.stringify(li) //对象转化成字符串
                            if(obj.status){
                                location.reload();
                            }else{
                                $('#error_msg').text(obj.error)
                            }
                        }
                    })
                })
            })
        })
    </script>
</body>
</html>
3.models.py
from django.db import models



class Business(models.Model):
    caption = models.CharField(max_length=32)
    code = models.CharField(max_length=32,null=True,default='SA')


class Host(models.Model):
    nid = models.AutoField(primary_key=True)
    hostname = models.CharField(max_length=32,db_index=True)
    ip = models.GenericIPAddressField(protocol='ipv4',db_index=True)
    port = models.IntegerField()
    b = models.ForeignKey(to="Business",to_field='id')
4.urls.py
from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^host/',views.host),
    url(r'^test_ajax/',views.test_ajax),
]

 三)一对多操作-编辑

1.views.py
def test_ajax(request):
    import json
    ret = {'status':True,'error':None,'data':None}
    try:
        h = request.POST.get('hostname')
        i = request.POST.get('ip')
        p = request.POST.get('port')
        b = request.POST.get('b_id')
        if h and len(h) > 5:

            models.Host.objects.create(
                hostname = h,
                ip = i,
                port = p,
                b_id = b
            )
            return HttpResponse('ok')
        else:
            ret['status'] = False
            ret['error'] = '太短了'
    except Exception as e:
        ret['status'] = False
        ret['error'] = '请求错误'

    return HttpResponse(json.dumps(ret))   #字段转化成字符串

四)多对多操作

1)基础操作

#方式一:自定义多对多关系表
# class Host(models.Model):
#     nid = models.AutoField(primary_key=True)
#     hostname = models.CharField(max_length=32,db_index=True)
#     ip = models.GenericIPAddressField(protocol='ipv4',db_index=True)
#     port = models.IntegerField()
#     b = models.ForeignKey(to="Business",to_field='id')
#
#
# class Application(models.Model):
#     name = models.CharField(max_length=32)
#
# class HostToApp(models.Model):
#     hobj = models.ForeignKey(to='Host',to_field='nid')
#     aobj = models.ForeignKey(to='Application',to_field='id')


#方法二:自动创建关系表
# class Host(models.Model):
#     nid = models.AutoField(primary_key=True)
#     hostname = models.CharField(max_length=32,db_index=True)
#     ip = models.GenericIPAddressField(protocol='ipv4',db_index=True)
#     port = models.IntegerField()
#     b = models.ForeignKey(to="Business",to_field='id')
#
#
# class Application(models.Model):
#     name = models.CharField(max_length=32)
#     r = models.ManyToManyField("Host")

# obj = Application.objects.get(id=1)
# 添加:
#
# obj.name
# #一下对第三张表的操作
# obj.r.add(1)   增加一条Application id =1 Host id=1的关系
# obj.r.add(*[1,2,3,4])增加Application id = 1 Host id=1,2,3,4关系4条记录
#
# 删除:
# obj.r.remove(1)
# obj.r.remove(2,4)
# obj.r.remove(*[1,2,3])
#
# obj.r.clear()  删除Application id=1的所有记录
#
# 更新:
# obj.r.set([3,5,7])  )。把所有Application id=1的删除,然后添加(1,3)(1,5)(1,7)
# 获取:
# obj.r.all()   #所有相关的主机对象'列表' QuerySet类型

方法三:
class Blog(models.Model):
site = models.CharField(max_length=32)
m = models.ManyToManyField('Tag',through='B2T',through_fields=['b','t1'])
#m不能进行add,remove,set改等操作,但可进行查询。因为第三张关系表的字段数不确定。但可以在通过m直接拿到Tag表的数据

class Tag(models.Model):
name = models.CharField(max_length=32)

class B2T(models.Model):
b = models.ForeignKey('Blog')
t1 = models.ForeignKey('Tag')
t2 = models.ForeignKey('abc')

2)实例--查询

1.vews.py
def app(request):
    if request.method == "GET":
        app_list = models.Application.objects.all()
        host_list = models.Host.objects.all()
        # for row in app_list:
        #     print(row.name,row.r.all())
        return render(request,'app.html',{"app_list":app_list,"host_list":host_list})
    elif request.method == "POST":
        app_name = request.POST.get('app_name')
        host_list = request.POST.getlist('host_list')

        print(app_name,host_list)
        obj = models.Application.objects.create(name=app_name)
        obj.r.add(*host_list)
        return redirect('/app/')

def ajax_add_app(request):
    ret = {'status':True,'error':None,'data':None}
    print(request.POST.get('app_name'),request.POST.getlist('host_list'))
    #request.POST.get('host_list')---->获取列表的最后一个元素
    #request.POST.getlist('host_list')---->获取整个列表
    app_name = request.POST.get('app_name')
    host_list = request.POST.getlist('host_list')
    obj = models.Application.objects.create(name=app_name)
    obj.r.add(*host_list)
    return HttpResponse(json.dumps(ret))
2.app.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .hide{
            display:none;
        }
        .shade{
            position:fixed;
            top:0;
            right:0;
            left:0;
            bottom:0;
            background:black;
            opacity:0.6;
            z-index:100;
        }
        .add-modal,.edit-modal{
            position:fixed;
            height:300px;
            width:400px;
            top:100px;
            left:50%;
            border:1px solid red;
            z-index:102;
        }

    </style>
</head>
<body>
    <h1>应用列表</h1>
    <div>
        <input type="button" id="add_app" value="添加">
    </div>
    <table border="1">
        <thead>
            <tr>
                <td>应用程序名称</td>
                <td>应用主机列表</td>
            </tr>
        </thead>
        <tbody>
            {% for app in app_list %}
                <tr>
                    <td>{{ app.name }}</td>
                    <td>
                        {% for host in app.r.all %}
                        <span>{{ host.hostname }}</span>
                        {% endfor %}
                    </td>
                </tr>
            {% endfor %}
        </tbody>
    </table>
    <div class="shade hide"></div>
    <div class="add-modal hide">
        <form id="add_form" method="POST" action="/app/">
        <div class="group">
            <input id='app_name' type="text" placeholder="应用程序名称" name="app_name" />
        </div>

        <div class="group" >
            <select id="host_list" name="host_list"  multiple>
                {% for op in host_list %}
                    <option value="{{ op.nid }}">{{ op.hostname }}</option>
                {% endfor %}
            </select>
        </div>
        <input type="submit" value="提交">
        <a id="add_submit_ajax" style="dispaly:none-block;background:blue;color:white">悄悄提交</a>
        <input id='cancel' type="button" value="取消">
        <span id="error_msg"></span>
        </form>
    </div>
    <div class="edit-modal hide">
        <form id="edit_form" method="POST" action="">

            <input type="text" name="nid" style="display: none" value="">
            <input id='host' type="text" placeholder="主机名" name="hostname" />
            <input id="ip" type="text" placeholder="IP" name="ip" />
            <input id="port" type="text" placeholder="端口" name="port" />
            <select id="sel" name="b_id">
                {% for op in b_list %}
                    <option value="{{ op.id }}">{{ op.caption }}</option>

                {% endfor %}
            </select>
            <a id="ajax_submit" style="display:inline-block;background:blue;color:white">编辑</a>
            <input id='cancel' type="button" value="取消">
            <span id="error_msg"></span>
        </form>
    </div>
    <script src="/static/jquery.min.js"></script>
    <script>
        $(function(){
            $('#add_app').click(function(){
                    $('.shade,.add-modal').removeClass('hide');
                });
            $('#cancel').click(function(){
                    $('.shade,.add-modal').addClass('hide');
                });
            $('#add_submit_ajax').click(function(){
                  $.ajax({
                      url:'/ajax_add_app/',
                      data:$('#add_form').serialize(),
                      type:"POST",
                      dataType:'JSON',
                      traditional:true,   //当data数据有列表时,需要添加此项
                      success:function(obj){
                          //JSON.parse(data)
                          console.log(obj)

                      },
                      error:function(){

                      }
                  })
            })
        })
    </script>
</body>
</html>
3.models.py
class Host(models.Model):
    nid = models.AutoField(primary_key=True)
    hostname = models.CharField(max_length=32,db_index=True)
    ip = models.GenericIPAddressField(protocol='ipv4',db_index=True)
    port = models.IntegerField()
    b = models.ForeignKey(to="Business",to_field='id')


class Application(models.Model):
    name = models.CharField(max_length=32)
    r = models.ManyToManyField("Host")

4.urls.py
from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^host/',views.host),
url(r'^test_ajax/',views.test_ajax),
url(r'^update_data/',views.update_data),
url(r'^app/',views.app),
url(r'^ajax_add_app/',views.ajax_add_app),
]

 五)多表操作相关参数

ForeignKey(ForeignObject) # ForeignObject(RelatedField)
        to,                         # 要进行关联的表名
        to_field=None,              # 要关联的表中的字段名称
        on_delete=None,             # 当删除关联表中的数据时,当前表与其关联的行的行为
                                        - models.CASCADE,删除关联数据,与之关联也删除
                                        - models.DO_NOTHING,删除关联数据,引发错误IntegrityError
                                        - models.PROTECT,删除关联数据,引发错误ProtectedError
                                        - models.SET_NULL,删除关联数据,与之关联的值设置为null(前提FK字段需要设置为可空)
                                        - models.SET_DEFAULT,删除关联数据,与之关联的值设置为默认值(前提FK字段需要设置默认值)
                                        - models.SET,删除关联数据,
                                                      a. 与之关联的值设置为指定值,设置:models.SET(值)
                                                      b. 与之关联的值设置为可执行对象的返回值,设置:models.SET(可执行对象)

                                                        def func():
                                                            return 10

                                                        class MyModel(models.Model):
                                                            user = models.ForeignKey(
                                                                to="User",
                                                                to_field="id"
                                                                on_delete=models.SET(func),)
        related_name=None,          # 反向操作时,使用的字段名,用于代替 【表名_set】 如: obj.表名_set.all()
        related_query_name=None,    # 反向操作时,使用的连接前缀,用于替换【表名】     如: models.UserGroup.objects.filter(表名__字段名=1).values('表名__字段名')
        limit_choices_to=None,      # 在Admin或ModelForm中显示关联数据时,提供的条件:
                                    # 如:
                                            - limit_choices_to={'nid__gt': 5}
                                            - limit_choices_to=lambda : {'nid__gt': 5}

                                            from django.db.models import Q
                                            - limit_choices_to=Q(nid__gt=10)
                                            - limit_choices_to=Q(nid=8) | Q(nid__gt=10)
                                            - limit_choices_to=lambda : Q(Q(nid=8) | Q(nid__gt=10)) & Q(caption='root')
        db_constraint=True          # 是否在数据库中创建外键约束
        parent_link=False           # 在Admin中是否显示关联数据


    OneToOneField(ForeignKey)
        to,                         # 要进行关联的表名
        to_field=None               # 要关联的表中的字段名称
        on_delete=None,             # 当删除关联表中的数据时,当前表与其关联的行的行为

                                    ###### 对于一对一 ######
                                    # 1. 一对一其实就是 一对多 + 唯一索引
                                    # 2.当两个类之间有继承关系时,默认会创建一个一对一字段
                                    # 如下会在A表中额外增加一个c_ptr_id列且唯一:
                                            class C(models.Model):
                                                nid = models.AutoField(primary_key=True)
                                                part = models.CharField(max_length=12)

                                            class A(C):
                                                id = models.AutoField(primary_key=True)
                                                code = models.CharField(max_length=1)

    ManyToManyField(RelatedField)
        to,                         # 要进行关联的表名
        related_name=None,          # 反向操作时,使用的字段名,用于代替 【表名_set】 如: obj.表名_set.all()
        related_query_name=None,    # 反向操作时,使用的连接前缀,用于替换【表名】     如: models.UserGroup.objects.filter(表名__字段名=1).values('表名__字段名')
        limit_choices_to=None,      # 在Admin或ModelForm中显示关联数据时,提供的条件:
                                    # 如:
                                            - limit_choices_to={'nid__gt': 5}
                                            - limit_choices_to=lambda : {'nid__gt': 5}

                                            from django.db.models import Q
                                            - limit_choices_to=Q(nid__gt=10)
                                            - limit_choices_to=Q(nid=8) | Q(nid__gt=10)
                                            - limit_choices_to=lambda : Q(Q(nid=8) | Q(nid__gt=10)) & Q(caption='root')
        symmetrical=None,           # 仅用于多对多自关联时,symmetrical用于指定内部是否创建反向操作的字段
                                    # 做如下操作时,不同的symmetrical会有不同的可选字段
                                        models.BB.objects.filter(...)

                                        # 可选字段有:code, id, m1
                                            class BB(models.Model):

                                            code = models.CharField(max_length=12)
                                            m1 = models.ManyToManyField('self',symmetrical=True)

                                        # 可选字段有: bb, code, id, m1
                                            class BB(models.Model):

                                            code = models.CharField(max_length=12)
                                            m1 = models.ManyToManyField('self',symmetrical=False)

        through=None,               # 自定义第三张表时,使用字段用于指定关系表
        through_fields=None,        # 自定义第三张表时,使用字段用于指定关系表中那些字段做多对多关系表
                                        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_constraint=True,         # 是否在数据库中创建外键约束
        db_table=None,              # 默认创建第三张表时,数据库中表的名称

 

posted @ 2017-04-29 10:38  jidi_78  阅读(104)  评论(0)    收藏  举报