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

相关文章
相关标签/搜索