guopengfa
发布于 2022-09-29 / 1490 阅读 / 0 评论 / 0 点赞

Django Basic

Django create project

django-admin startproject YourProjectName

Django create app

python manage.py startapp YourAppName

Django above models

from django.db import models
 
 
# Create your models here.
 
class Author(models.Model):
    author_name = models.CharField(max_length=8, null=False)
 
 
class AuthorDetail(models.Model):
    author_sex = models.IntegerField(choices=((0, "男"), (1, "女")), null=False)
    author_phone  = models.CharField(max_length=11,null=False)
    author_age = models.IntegerField(null=False)
    #一对一关系的两个类,关系模型写到哪个类里都行,但是代码是顺序执行的,如果放在第一个类,在执行
    #到对应表格时,还没有创建,所以要写到第二个类里
    #models.CASCADE是级联删除,即关系方数据删掉,本表的相关信息也一并删掉,可参考前面的外键博客
    author = models.OneToOneField(to=Author,to_field="id",on_delete=models.CASCADE)
 
class Publisher(models.Model):
    publisher_name  = models.CharField(max_length=30,null=False)
    publisher_address = models.CharField(max_length=50,null=False)
    publisher_city = models.CharField(max_length=30,null=False)
    publisher_website = models.URLField(null=True)
 
class Book(models.Model):
    book_name = models.CharField(max_length=20,null=False)
    #多对多关系与一对一关系同理,写到哪个都行,也是顾及代码执行顺序,要写到下面的类里
    author  = models.ManyToManyField(to=Author)
    #一对多关系,要写到多的类里
    publisher = models.ForeignKey(to=Publisher,to_field="id",on_delete=models.CASCADE)
    price  = models.FloatField(max_length=6,null=None)
    
# from : https://blog.csdn.net/weixin_43258703/article/details/122809198

Django register model into admin web page

# file at: projectPath/AppPath/admin.py

from django.contrib import admin
from test1.models import Country, City

# Register your models here.
admin.site.register(Country)
admin.site.register(City)

Django create admin user

python manage.py createsuperuser

Django management multi databases

# You must add the  database router at project default folder
from: ProjectName/application/databases_router.py
edit this file to support router mapping settings.
for example:
# -*- coding: utf-8 -*-
from django.conf import settings
DATABASE_MAPPING = settings.DATABASE_APPS_MAPPING


class DatabaseAppsRouter(object):
    """
    A router to control all database operations on models for different
    databases.

    In case an app is not set in settings.DATABASE_APPS_MAPPING, the router
    will fallback to the `default` database.

    Settings example:

    DATABASE_APPS_MAPPING = {'app1': 'db1', 'app2': 'db2'}
    """

    def db_for_read(self, model, **hints):
        """
        Point all read operations to the specific database.
        """
        if model._meta.app_label in DATABASE_MAPPING:
            return DATABASE_MAPPING[model._meta.app_label]
        return None

    def db_for_write(self, model, **hints):
        """
        Point all write operations to the specific database.
        """
        if model._meta.app_label in DATABASE_MAPPING:
            return DATABASE_MAPPING[model._meta.app_label]
        return None

    def allow_relation(self, obj1, obj2, **hints):
        """
        Allow any relation between apps that use the same database.
        """
        db_obj1 = DATABASE_MAPPING.get(obj1._meta.app_label)
        db_obj2 = DATABASE_MAPPING.get(obj2._meta.app_label)
        return True  # Allow all relationship
        # if db_obj1 and db_obj2:
        #     if db_obj1 == db_obj2:
        #         return True
        #     else:
        #         return False
        # return None

    # for Django 1.4 - Django 1.6
    def allow_syncdb(self, db, model):
        """
        Make sure that apps only appear in the related database.
        """

        if db in DATABASE_MAPPING.values():
            return DATABASE_MAPPING.get(model._meta.app_label) == db
        elif model._meta.app_label in DATABASE_MAPPING:
            return False
        return None

    # Django 1.7 - Django 1.11
    def allow_migrate(self, db, app_label, model_name=None, **hints):
        # print db, app_label, model_name, hints
        if db in DATABASE_MAPPING.values():
            return DATABASE_MAPPING.get(app_label) == db
        elif app_label in DATABASE_MAPPING:
            return False
        return None

and edit settings.py to add second database and mapping settings too

DATABASES = {
    "default": {
        "ENGINE": DATABASE_ENGINE,
        "NAME": DATABASE_NAME,
        "USER": DATABASE_USER,
        "PASSWORD": DATABASE_PASSWORD,
        "HOST": DATABASE_HOST,
        "PORT": DATABASE_PORT,
    },
    'clean_zombie': {
        "ENGINE": DATABASE_ENGINE,
        "NAME": DATABASE_NAME_zombie,
        "USER": DATABASE_USER_zombie,
        "PASSWORD": DATABASE_PASSWORD_zombie,
        "HOST": DATABASE_HOST,
        "PORT": DATABASE_PORT,
    }
}
from settings file:
DATABASE_APPS_MAPPING = {'zombie': 'clean_zombie', 'system': 'default', 'crud_demo': 'clean_zombie',
                         'drf_yasg': 'default',
                         'captcha': 'default', 'auth': 'default', 'contenttypes': 'default', 'sessions': 'default',
                         'messages': 'default', 'staticfiles': 'default', 'django_comment_migrate': 'default',
                         'rest_framework': 'default', 'django_filters': 'default', 'corsheaders': 'default'}

About migrate

when you have multidatabase in your project
python manage migrations  # this will apply all database change
python manage migrate  # this will default to apply your default model change. if you want to apply other database change ,you should add the argument: --database [Database name]

Add existed table

if table exsited, You just want to use it, and not management it.
You just to add managed=False, at class Meta, like blow:

class TestModel(model.Model):
	te = models.IntegerField()
    
    class Meta:
    	managed = False

Django self admin page import or export data

# see detail to url: https://www.cnblogs.com/pcent/p/10809136.html
# source add field for ForeignKey: 

class ShopResource(resources.ModelResource):
    source_field = fields.Field(attribute='source_field', column_name='Fied_Name', widget=ForeignKeyWidget(YourSourceModel, 'source_field'))

评论