zoukankan      html  css  js  c++  java
  • django7 models 高级应用

    ===================models 中 related_name   的用法:

    class A():

      title=models.CharField()

      name=models.CharField()

    class B():

      fk1=models.ForKeing(to='A',related_name='r1')

      fk2=models.ForKeing(to='A',related_name='r1')

    当 以上这种情况   表B  有俩个 字段 都和 表A 关联 

    表A 做反向查找的时候 就不能  

    obj=models.A.objects.get(id=1)

    obj.B_set.all()  

    以为无法确定是 B的哪个FK

    但是 用related_name  就可以确认出来 

    B.r1.all()

    B.r2.all()

    ***************************************through_fields 

    class A():

      title=models.CharField()

      name=models.CharField()

    class B():

    user=models.CharField()

      fk1=models.ForKeing(to='A',related_name='r1')

      fk2=models.ForKeing(to='A',related_name='r1')

    like=models.ManyToMany(to='B',throuogh='Like',through_fields=('user','name'))

    class Like():
    user=models.ForeignKey(to='B')
    name=models.ForeignKey(to='A')
    ctime=models.DataTimeField()

    在多对多的情况下:
    ManyToMany字段 默认 会生成第三张表,但是 只有3个ID,如果再想加其他字段
    需要自己创建第三张表,然后 通过参数关联
    models.ManyToMany(to='B',throuogh='Like',hrough_fields=('user','name'))

    其中 through_fields 代表第三张表 关联的俩个字字段,而第一个值必须是 第三张表关联自己(B表)的字段,
    第二个值是第三张表中关联另外一张表(A表)的值

    -------------------------------------------------------联合唯一索引

    class A():

      title=models.CharField()

      name=models.CharField()

    class B():

    user=models.CharField()

      fk1=models.ForKeing(to='A',related_name='r1')

      fk2=models.ForKeing(to='A',related_name='r1')

    like=models.ManyToMany(to='B',throuogh='Like',through_fields=('user','name'))

    class Like():
    user=models.ForeignKey(to='B')
    name=models.ForeignKey(to='A')
    ctime=models.DataTimeField()

    class Meta:
    unique_together = [
    ('user', 'name'),
    ]

    user和 name  联合唯一索引

    ===============================

  • 相关阅读:
    计算机基础
    程序的控制结构
    day 04作业
    数据类型-数据类型
    第二次作业
    第二次博客
    第一篇博客
    原生js与ajax应用
    ajax原理及其优缺点
    jQuery动画
  • 原文地址:https://www.cnblogs.com/onda/p/7602259.html
Copyright © 2011-2022 走看看