I. Self-correlation
Write a good blog: https://www.cnblogs.com/Kingfan1993/p/9936541.html
1. One-to-many Association
1. Intra-table self-association refers to that the objects and tables associated with the data in the table are the same fields, so we can directly set the foreign key Association into the fields of our own table by using intra-table association.
2. For example, for microblog comments, each comment may have sub-comments, but the field content of each comment should be the same, and each comment has only one parent comment, which satisfies the one-to-many situation. The parent comment id is an associated field and can correspond to multiple sub-comments.
3. Foreign key association is in the sub-comment, the related field is the sub-comment, the sub-comment is positive, and the parent comment is negative.
4. One-to-many self-association can be used in BBS forum message function.
# In models.py # Table of articles """ id title content 1 'hello' 'nihao....' 2 'world' 'shijie....' """ class Article(models.Model): title = models.CharField(max_length=32) content = models.CharField(max_length=500) # Comments """ id article_id content reply_id(Self-association, as the primary key of a foreign key to associate its own table id) uid 1 1 'cool' 0 (Not a response to any comment) 2 1 'hehe' 0 3 1 'wtf' 1 (It means that the comment is a reply. id Comments for 1) 4 1 'how' 0 5 2 'haha' 0 6 1 'wow' 1 (It's also the first comment in the response.) 7 2 'Um' 5 (Reply to Article 5 Comments) 8 1 'aha' 3 (Reply to the third comment) """ class Comment(models.Model): article = models.ForeignKey("Article") content = models.CharField(max_length=255) reply = models.ForeignKey("Comment", default=0)
2. Many-to-many Association
1. For example, if we create a list of matches with men and women, we can build many-to-many relationships through self-association.
2. Associate foreign keys with their primary key id through ManyToManyField
# In models.py class User(models.Model): name = models.CharField(max_length=32) gender_list = [ (1, "male"), (2, "female"), ] gender = models.IntegerField(choices=gender_list,default=1) r = models.ManyToManyField("User")
3. After submitting the table model through Python 3 management. py makemigrations and python 3 management. py migrates, two tables are generated, one is the main table and the other is the slave table.
App_user table and app_user_r table
4. Two fields in the slave table, one is from_primary table name_id and the other is to_primary table name_id.
5. When we look up the objects associated with to_primary table name_id through the objects associated with from_primary table name_id, we can directly query through'primary table object. relational table (slave table)'
# views.py # Query and jojo Girls res = models.User.objects.filter(name='jojo', gender=1).first() #print(res) # object objs = res.m.all() for obj in objs: print(obj.name) ''' Corresponding SQL statements: 1. select * from app01_user_m where from_user_id = 1; The result is the object corresponding to the data in the app_user_r table: to_user_id=[3,4]. 2. select * from app01_user where id in (3,4); '''
6. When we look up the objects associated with to_primary table name_id through the objects associated with to_primary table name_id, we need to query through'primary table object. relational table_set'.
# views.py # Search for guys dating fanbingbing res = models.User.objects.filter(name='fanbingbing', gender=2).first() objs = res.user_set.all() for obj in objs: print(obj.name) ''' Corresponding SQL statements: 1. select * from app01_user_m where to_user_id = 3; The result is the object corresponding to the data in the app_user_r table: from_user_id=[1,2] 2. select * from app01_user where id in (1,2); '''
II. Auh Module
1. Simple use of auth
1. When executing the two commands of database migration, will django create many tables even if we don't build tables? Let's look at a table called auth_user after we create it. Since it's a table, there must be a corresponding way to change the table.
2. Record addition of auth_user table: Create super user, not insert manually, because the password is encrypted, the plaintext password added manually is meaningless.
3. We can use run management. py Task in Tools in the navigation bar to enter create superuser in pycharm.
# views.py # You can use auth authentication to make a simple login. from django.contrib import auth def test(request): if request.method == "GET": return render(request,"test.html") else: name = request.POST.get("user") psw = request.POST.get("psw") myuser = auth.authenticate(request,username=name,password=psw) # If this record is in the auth_user table, a user object (usually the user name) is returned. if myuser: auth.login(request,myuser) # A user object is generated that can be called in any view function """ //To save the login status for the current successful login users, previously through cookie or session, now through auth; request.session["name"] = name Equivalent to: auth.login(request,myuser) """ return HttpResponse("success") else: return redirect("/test/") # Demonstrate in other view functions def other(request): print(request.user) print(request.user.is_authenticated) return HttpResponse("ok")
# Summary: # 1. As long as the login successfully executes auth.login(request,user) # The current logged-in user object can then be retrieved through request.user in any other view function. # 2. When auth.login is not executed, request.user prints out anonymous users. Deleting session table data demonstrates this effect # 3. How to determine whether the request.user logs in through auth.login? request.user.is_authenticated, print: print(request.user.is_authenticated) # Why can you get the current login object through request.user in other view functions after auth.login is executed? # There is no Middleware in Django called'django. contrib. auth. middleware. Authentication Middleware'. What did it do? Can you deduce it? # Retrieve session from the web side to look up the corresponding data in the django_session table
4. Cancellation
auth.logout(request) # Equivalent to deleting session data request.session.flush()
2. Decorators
# Decorator check whether landing and jumping from django.contrib.auth.decorators import login_required @login_required(login_url='/login/',redirect_field_name='old') # If you don't log in, you will jump to the login page, and then splice the page path / login/?old=/my_view/, which you wanted to visit last time. You can modify the next key name through the redirect_field_name parameter (if you don't write this parameter, it's 127.0.0.1:8090/login/?old=/my_view/, which is useless) def my_view(request): return HttpResponse("ok")
If all of my view functions need to be decorated and jumped to the login page, it will be cumbersome and we can configure them in the settings.py file under the project.
# settings.py # You can specify an auth check login in the configuration file to jump to a path illegally and uniformly LOGIN_URL = '/login/' # It can be configured either globally or locally.
3. Implementing the registration function through auth
1. In addition to input from the command line, we can add data to the auth_user table through other methods provided by auth.
# views.py file of app from django.contrib.auth.models import User def register(request): if request.method == "GET": return render(request, "register.html") else: user_name = request.POST.get("username") psw = request.POST.get("psw") # User.objects.create() # You can't use this because the password is plaintext. User.objects.create_user(username=user_name,password=psw) # Creating Ordinary Users # User.objects.create_superuser(username=user_name,password=psw,email=233@qq.com) # Creating Super Users
4. Modify passwords
def modify(request): if request.method=='GET': return render(request, 'modify.html') else: oldpsw = request.POST.get('oldpsw') newpsw = request.POST.get('newpsw') res = request.user.check_password(oldpsw) # Get the password print(res) if res: request.user.set_password(newpsw) request.user.save() return HttpResponse('ok') else: return render(request, 'modify.html')
5. Application of auth function in custom model table
1. Extended auth_user table
2. One-to-one Association (not recommended)
from django.contrib.auth.model s import User class UserDetail(models.Models): phone_number = models.CharField(max_length=11) user = models.OnoToOneField(to=User)
3. Object-Oriented Inheritance
- You need to configure it in the settings.py file under the project
# settings.py """ 1.Specify that I no longer use the default auth_user Tables are created by myself. Userinfo surface 2.After customizing the default tables used by the authentication system, we can use the default tables as well. auth_user The table uses our UserInfo It is shown. 3.Not in the library. auth_user Watch, original auth The operation method of tables can be realized by using custom tables. """ # AUTH_USER_MODEL= "Model Table Name Corresponding to App Name. models" AUTH_USER_MODEL = "app01.User"
- You can create your own user information table in the models.py file under app
# In models.py from django.contrib.auth.models import User,AbstractUser # Inheritance of user table in auth class UserInfo(AbstractUser): phone_number = models.CharField(max_length=32)