• related_name和related_query_name举例区别


    举例,一

    class UserInfo(models.Model):
        nickname = models.CharField(max_length=32)
        username = models.CharField(max_length=32)
        password = models.CharField(max_length=64)
    
        gender_choices = (
            (1,'男'),
            (2,'女'),
        )
        gender = models.IntegerField(choices=gender_choices)
    
    ralated_query_name 
    class U2U(models.Model):
        g = models.ForeignKey('UserInfo',ralated_query_name='a')
        b = models.ForeignKey('UserInfo',ralated_query_name='b')
    
       # ralated_query_name
    
      #  obj.对象男.b_set.all()
      #  obj.对象女.a_set.all()
    

    ralated_name
    class U2U(models.Model):
        g = models.ForeignKey('UserInfo',ralated_name='a')
        b = models.ForeignKey('UserInfo',ralated_name='b')
    
       # ralated_name
    
      #  obj.对象男.b.all()
      #  obj.对象女.a.all()
    

     回顾以往例子:反向查找别名替换

    class UserType(models.Model):
        title = models.CharField(max_length=32)
    
    class User(models.Model):
        username = models.CharField(max_length=32)
        ut = models.ForeignKey('UserType',related_name='xxx')
    
    ## related_name='xxx'
    反向:小写表名user_set ===>xxx
    ## related_query_name = 'xxx'
    反向:user_set==>xxx_set

    推荐用:
     ut = models.ForeignKey('UserType',related_name='users')

        obj.users

    
    
    #M2M自关联的特性:
    ##1,obj.m  前一列
    ##2,obj.userinfo_set 后一列
    
    obj = models.UserInfo.objects.filter(id=1).first()
    
    #男---前一列
    obj.m    =>select xx from xx where  from_userinfo_id = 1
    
    #女----后一列
    obj.userinfo_set =>select xx from xx where to_userinfo_id = 1
    

      

    定义:

    前面列:男生ID

    后面列:女生ID

    应用:  

    #男生obj
    obj = models.UserInfo.objects.filter(id=1).first()
    # 根据男生id=1,查找关联的所有女生
    obj.m.all()
     
    
    #女生obj
    obj = models.UserInfo.objects.filter(id=4).first()
    #根据女生id=4,查找关联的所有男生
    obj.userinfo_set.all()
    

      # FK自关联

    
    
    
    
    
    
    
    
    

     

  • 相关阅读:
    c++ accumulate
    Croc Champ 2013 Round 2 (Div. 2 Edition) B. Ksusha the Squirrel
    ural 1017. Staircases
    ural 1012Kbased Numbers. Version 2 1013. Kbased Numbers. Version 3
    ural 1008. Image Encoding
    ural 1009. Kbased Numbers
    echo命令去掉换行符
    linux中shell 参数变量
    C#中可变字符串StringBuilder和String
    C#异常处理语句
  • 原文地址:https://www.cnblogs.com/catherine007/p/8997955.html
Copyright © 2020-2023  润新知