django第一個app,2

1,數據庫設置html

上一應用是使用默認數據sqlites,可自行設置綁定數據庫,參數python

ENGINE – Either 'django.db.backends.sqlite3''django.db.backends.postgresql''django.db.backends.mysql', or 'django.db.backends.oracle'mysql

name 數據庫名稱,須要用絕對路徑,默認值是os.path.join(BASE_DIR, 'db.sqlite3')sql

settings.py文件裏面列出項目正在使用的app,shell

默認app有,admin ,auth ,contenttypes,sessions,messages,staticfiles數據庫

這些app裏面會用到數據庫表,經過命令建立表django

$ python manage.py migrate

2 建立本身的modelsapi

polls/models.pysession

from django.db import models


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

添加到setting的apporacle

mysite/settings.py

INSTALLED_APPS = [
    'polls.apps.PollsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

生成migrations

python manage.py makemigrations polls

查看生成表細節

python manage.py sqlmigrate polls 0001

能夠查看 polls/migrations/0001_initial.py 裏面生成表的細節,會自動生成自增id字段(能夠被重寫),會生成表名_id的關聯字段

不關乎數據庫,migrations 的檢查項目

python manage.py check

生成表:

python manage.py migrate

後面若是須要修改表,不須要刪刪表,丟失數據

3,項目api的使用

python manage.py shell
>>> from polls.models import Question, Choice   # Import the model classes we just wrote.

# No questions are in the system yet.
>>> Question.objects.all()
<QuerySet []>
>>> from django.utils import timezone
>>> q = Question(question_text="What's new?", pub_date=timezone.now())

# Save the object into the database. You have to call save() explicitly.
>>> q.save()

# Now it has an ID.
>>> q.id
1

改變對象對外顯示字符字符安

def __str__(self):
        return self.question_text

在類裏面添加方法

def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

一對多查詢,新增

>>> q = Question.objects.get(pk=1)

# Display any choices from the related object set -- none so far.
>>> q.choice_set.all()
<QuerySet []>

# Create three choices.
>>> q.choice_set.create(choice_text='Not much', votes=0)
<Choice: Not much>
>>> q.choice_set.create(choice_text='The sky', votes=0)
<Choice: The sky>
>>> from django.utils import timezone
>>> current_year = timezone.now().year

q.choice_set.count()

多對一查 刪除

>>> Choice.objects.filter(question__pub_date__year=current_year)
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>

# Let's delete one of the choices. Use delete() for that.
>>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
>>> c.delete()

4django admin 介紹

python manage.py createsuperuser,

在admin裏面註冊model後,即可實現增刪改查

polls/admin.py

from django.contrib import admin

from .models import Question

admin.site.register(Question)
    • null :缺省設置爲false.一般不將其用於字符型字段上,好比CharField,TextField上.字符型字段若是沒有值會返回空字符串。
    • blank:該字段是否能夠爲空。若是爲假,則必須有值
    • choices:一個用來選擇值的2維元組。第一個值是實際存儲的值,第二個用來方便進行選擇。如SEX_CHOICES= ((‘F’,'Female’),(‘M’,'Male’),)
    • core:db_column,db_index 若是爲真將爲此字段建立索引
    • default:設定缺省值
    • editable:若是爲假,admin模式下將不能改寫。缺省爲真
    • help_text:admin模式下幫助文檔
    • primary_key:設置主鍵,若是沒有設置django建立表時會自動加上:
1 id = meta.AutoField('ID', primary_key=True)
2 primary_key=True implies blank=False, null=False and unique=True. Only one primary key is allowed on an object.
  • radio_admin:用於admin模式下將select轉換爲radio顯示。只用於ForeignKey或者設置了choices
  • unique:數據惟一
  • unique_for_date:日期惟一,以下例中系統將不容許title和pub_date兩個都相同的數據重複出現
  • title = meta.CharField(maxlength=30,unique_for_date=’pub_date’)
  • unique_for_month / unique_for_year:用法同上
  • validator_list:有效性檢查。非有效產生 django.core.validators.ValidationError 錯誤

分類: Django

相關文章
相關標籤/搜索