django 創建管理員用戶


7.2 create 創建管理員用戶:
python manage.py run server
python manage.py createsuperuser
password :12345678912
7.3 admin.py 注冊模型:
from .models import Student,Grade

class Register(admin.ModelAdmin):
 7.3.1 #列表頁屬性
    list_display 展示數據庫字段名稱包含字段列
    list_filter過濾器過濾根據某個字段
    search_fields = ['user_name'] # 查詢篩選字段依據字段名稱,此字段不可以為外鍵類列
    list_per_page = 2   #數據庫分頁數量2 row 為一頁
    # 添加修改頁(注意fields和fieldsets不可以同時使用,只能存在以一個)
    #排序,只針對可編輯列,展示,對於pk不允許編輯
    #fields = ['user_name','is_man','is_delete','stu_id']
    #分組屬性,列表順序就是頁面展示順序
    fieldsets = [("basic",{"fields":["user_name","is_man"]}),
    ("junior",{"fields":["is_delete","stu_id"]})]

#注冊類
admin.site.register(Student,RegisterStudent)
admin.site.register(Grade,RegisterGrade)
7.4關聯對象
在admin.py里新建關聯對象class並且繼承admin.TabularInline類,引入需要被關聯的class model,以及關聯extra rows數量
class StudentGradeInfo(admin.TabularInline):
    # 聲明需要關聯模型對象屬性賦值
    model = Student
    # 關聯幾個row
    extra = 2
在需要展示引入模型的主模型中引入extra 的model對象:
  inlines = [StudentGradeInfo]
頁面布爾表達式自定義:
class RegisterStudent(admin.ModelAdmin):
    #重新定義屬性列展示名稱函數
    def zh_sex(self):
        if self.is_man:
            return "True"
        else:
            return "False"

    def delete_condition(self):
        if self.is_delete:
            return "yes"
        else:
            return "no"
    #web展示字段縮寫
    zh_sex.short_description = "性別"
    delete_condition.short_description = "在校"
    #動作展示位置調整
    actions_on_bottom = True
    actions_on_top = False
    # check box 選中計數顯示,false不顯示,true 顯示
    actions_selection_counter = False
    #引入重新定義的展示列為函數對象替換原有字符串如zh_index,delete_condition
    list_display = ['pk', 'user_name', zh_sex, 'createObj_date', delete_condition, 'stu_id']
FAQ:
Django 數據庫建表的時候 No migrations to apply原因出現和解決
rm -rf  0001_initial.py 進入數據庫delete from django_migrations where app="yourapplicationName";
執行: python manage.py makemigrations
python manage.py migrate
檢查結果顯示success:
Running migrations:
  Applying app.0001_initial... OK
one to one
one to many 與主鍵外鍵關系
一對一則需要sub table pr和Foreignkey 共用一個字段
一對多,sub table pr 和 Foreignkey 分開
主表的主鍵最好外鍵到子表的外鍵上,不能外鍵到sub table的pk column
FAQ:主表,sub 表刪除順序:必須先刪除子表在刪除主表由於子表外附與主鍵就像橘子皮附着在橘子肉上一樣,
想吃橘子必須先去皮,否則報錯如下情況:其次如果想刪除主表的數據而不是drop表並且繼續保留主表sub表數據可以先備份子表再刪除主表數據就可以了但是要建立級聯刪除關系:
需要在創建多對一的關系的,需要在Foreign的第二參數中加入on_delete=models.CASCADE  主外關系鍵中,級聯刪除,也就是當刪除主表的數據時候從表中的數據也隨着一起刪除
mysql> drop table app_grade;
ERROR 3730 (HY000): Cannot drop table 'app_grade' referenced by a foreign key constraint 'app_student_stu_id_id_eb16ae0c_fk_app_grade_grade_id' on table 'app_student'.
mysql> drop table app_student;
Query OK, 0 rows affected (0.02 sec)
mysql> drop table  app_grade;
Query OK, 0 rows affected (0.07 sec)

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM