Django使用Python操作数据库 --Django 1.8.2 文档(中文)部分笔记

原文网址
http://python.usyiyi.cn/django/intro/tutorial01.html
最好看过原文再阅读
model创建大致如下

#encoding=utf-8
from __future__ import unicode_literals

from django.db import models
from django.utils import timezone
import datetime 

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    def __str__(self):              # __unicode__ on Python 2
        return self.question_text
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

class Choice(models.Model):
    question = models.ForeignKey(Question)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    def __str__(self):              # __unicode__ on Python 2
        return self.choice_text     #the usage of this function:不仅会使你自己在使用交互式命令行时看得更加方便,而且会在Django自动生成的管理界面中使用对象的这种表示



# three step of change models
# 1.修改你的模型(在models.py文件中)。
# 2.运行python manage.py makemigrations ,为这些修改创建迁移文件
# 3.运行python manage.py migrate ,将这些改变更新到数据库中。

使用python manage.py shell进行数据库操作

#encoding=utf-8
>>> from polls.models import Question, Choice   # Import the model classes we just wrote.

# No questions are in the system yet.
#选择所有的Question
>>> Question.objects.all()
[]

# Create a new Question.
# Support for time zones is enabled in the default settings file, so
# Django expects a datetime with tzinfo for pub_date. Use timezone.now()
# instead of datetime.datetime.now() and it will do the right thing.
>>> from django.utils import timezone
#创建一个question对象
>>> 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. Note that this might say "1L" instead of "1", depending
# on which database you're using. That's no biggie; it just means your
# database backend prefers to return integers as Python long integer
# objects.
#获取Question的一些属性
>>> q.id
1

# Access model field values via Python attributes.
>>> q.question_text
"What's new?"
>>> q.pub_date
datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)

#修改属性并保存
# Change values by changing the attributes, then calling save().
>>> q.question_text = "What's up?"
>>> q.save()

#再次查询所有Question
# objects.all() displays all the questions in the database.
>>> Question.objects.all()
[<Question: Question object>]






#=======================================================================








>>> from polls.models import Question, Choice

# 添加__str__()方法后再次查询所有Question
# Make sure our __str__() addition worked.
>>> Question.objects.all()
[<Question: What's up?>]

# 使用过滤器查询
# Django provides a rich database lookup API that's entirely driven by
# keyword arguments.
>>> Question.objects.filter(id=1)
[<Question: What's up?>]
>>> Question.objects.filter(question_text__startswith='What')
[<Question: What's up?>]

# Get the question that was published this year.
>>> from django.utils import timezone
>>> current_year = timezone.now().year
>>> Question.objects.get(pub_date__year=current_year)
<Question: What's up?>

# Request an ID that doesn't exist, this will raise an exception.
>>> Question.objects.get(id=2)
Traceback (most recent call last):
    ...
DoesNotExist: Question matching query does not exist.


# pk应该就是primary key的意思?
# Lookup by a primary key is the most common case, so Django provides a
# shortcut for primary-key exact lookups.
# The following is identical to Question.objects.get(id=1).
>>> Question.objects.get(pk=1)
<Question: What's up?>

# Make sure our custom method worked.
>>> q = Question.objects.get(pk=1)
>>> q.was_published_recently()
True



# Give the Question a couple of Choices. The create call constructs(构建) a new
# Choice object, does the INSERT statement(陈述,声明), adds the choice to the set
# of available choices and returns the new Choice object. Django creates
# a set to hold the "other side" of a ForeignKey relation
# (e.g. a question's choice) which can be accessed via the API.
>>> q = Question.objects.get(pk=1)

# 通过相关的Question对象显示与其有关的Choice对象集合---目前还没有相关的Choice对象
# Display any choices from the related object set -- none so far.
>>> q.choice_set.all()
[]

# 使用Question对象的Choice集合创建Choice对象
# 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>
>>> c = q.choice_set.create(choice_text='Just hacking again', votes=0)


# Choice对象也有一些API来访问与其相关的Question对象
# Choice objects have API access to their related Question objects.
>>> c.question
<Question: What's up?>

# 而反之亦然
# And vice versa: Question objects get access to Choice objects.
>>> q.choice_set.all()
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
>>> q.choice_set.count()
3

# 查询一些Choice对象,这些Choice对象所属的Question对象的pub_date的年份为系统当前年份

# The API automatically follows relationships as far as you need.
# Use double underscores to separate relationships.
# This works as many levels deep as you want; there's no limit.
# Find all Choices for any question whose pub_date is in this year
# (reusing the 'current_year' variable we created above).
>>> Choice.objects.filter(question__pub_date__year=current_year)
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]

# 通过Question对象查询出Choice对象,删除
# Let's delete one of the choices. Use delete() for that.
>>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
>>> c.delete()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值