Django: foreign key relationship in the analysis ORM ForeignKey

 

Suppose there are two tables, Role and User, as a character corresponding to a plurality of users belongs to a foreign key, it uses User rolename a ForeignKey field, the first to link a parameter table Role, the second parameter related_name is used to reverse lookup there are several users with this role.

class Role (models.Model):
     '' ' 
    role table 
    ' '' 
    ROLE_NAME = models.CharField (MAX_LENGTH = 50 ) 
    the create_time = models.DateTimeField (auto_now_add = True) 
    Status = models.CharField (MAX_LENGTH = 10 ) 

    DEF  __str__ (Self ):
         return self.role_name 


class the user (models.Model):
     '' ' 
    the user information table, user table field ForeignKey role_name meaning foreign key, on behalf of a foreign key, a character corresponding to a plurality of users 
    ' '' 

    Gender = ( 
        ( ' MALE ' , ' male ' ),
        ('female', '')
    )
    member_code = models.CharField(max_length=20, unique=True)
    name = models.CharField(max_length=30)
    password = models.CharField(max_length=256)
    role_name = models.ForeignKey(Role, related_name='member_role', default=3)
    email = models.EmailField(max_length=50)
    sex = models.CharField(max_length=10, choices=gender, default='')
    create_time = models.DateTimeField(auto_now_add=True)
    status = models.CharField(max_length=10, default=1)

    def __str__(self):
        return self.name

  

 

 

note:

  Although the User table called ROLE_NAME field names, but because it is a foreign key, it will automatically add the field name in the actual table _id called role_name_id, the primary key value of the id field value table Role

demand:

  Gets role information corresponding to a person

  Code: 01010101 to obtain the role name membe_code corresponding to the user

from account.models import User

def user():
    user = User.objects.get(member_code='01010101')
    print user.role_name.role_name

user()

 

  doubt:

    Why here user.role_name.role_name way to use it?

  answer:

    Because user.role_name, returns Role objects, it is necessary to obtain the corresponding role name .role_name again, the same time want to get this role can create user.role_name.create_time

    But because there are objects Role model code readability

     def __str__(self):
          return self.role_name

    In fact, it can be directly user.role_name direct access to the role the user belongs to, but is not recommended for such use , especially after the background processing data need to be serialized, but user.role_name returns will complain when a target sequence;

    Or to obtain a corresponding primary table objects, particularly objects reacquisition primary table field values.

 

Guess you like

Origin www.cnblogs.com/gcgc/p/11245888.html