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

Django Basic

Django create project

django-admin startproject YourProjectName

Django create app

python 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)
    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 :

Django register model into admin web page

# file at: projectPath/AppPath/

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

# Register your models here.

Django create admin user

python createsuperuser

Django management multi databases

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

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

    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 to add second database and mapping settings too

    "default": {
    'clean_zombie': {
        "NAME": DATABASE_NAME_zombie,
        "USER": DATABASE_USER_zombie,
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:
# 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'))