【2】依照Django官网,创建一个web app 创建app/创建对应的数据库表
2015-08-17 00:28
676 查看
1. Creating app
$ python manage.py startapp pollsThat’ll create a directory polls,which is laid out like this:
polls/ __init__.py admin.py migrations/ __init__.py models.py tests.py views.py
1.1 Edit polls/models.py:
from django.db import models 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_textdef was_published_recently(self): return self.pub_date >= timezone.now()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 2return self.choice_text
1.2 Edit the mysite/settings.py file again, and change the INSTALLED_APPS setting to include the string 'polls':
INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls', )
1.3 Now Django knows to include the polls app. Let’s run another command:
$ python manage.py makemigrations polls
1.4 Now, run migrate again to create those model tables in your database:
1.4.1 python manage.py check;
1.4.2 python manage.py migrate
1.5Playing with the API
1.5.1 python manage.py shell 1.5.2>>> from polls.models import Question, Choice # Import the model classes we just wrote. # No questions are in the system yet. >>> 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 >>> 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. >>> 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() # objects.all() displays all the questions in the database. >>> Question.objects.all() [<Question: Question object>]>>> from polls.models import Question, Choice# 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.# 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)# Display any choices from the related object set -- none so far.>>> q.choice_set.all()[]# 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 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# 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>]# Let's delete one of the choices. Use delete() for that.>>> c = q.choice_set.filter(choice_text__startswith='Just hacking')>>> c.delete()
相关文章推荐
- windows+apache+mod_python配置django运行环境
- python Django连接MySQL数据库做增删改查
- django自定义Field实现一个字段存储以逗号分隔的字符串
- 在Python的Django框架中加载模版的方法
- 在Django中使用Sitemap的方法讲解
- 详解Django中的form库的使用
- Django中的CACHE_BACKEND参数和站点级Cache设置
- 剖析Django中模版标签的解析与参数传递
- Python中DJANGO简单测试实例
- Python的Django框架中的数据库配置指南
- 在Django的上下文中设置变量的方法
- 在Python的Django框架中编写编译函数
- 在Django的URLconf中进行函数导入的方法
- 在Python的Django框架中生成CSV文件的方法
- 在主机商的共享服务器上部署Django站点的方法
- 使用Python的Django框架中的压缩组件Django Compressor
- 对于Python的Django框架部署的一些建议
- Djang中静态文件配置方法
- Python的Django框架中的Context使用
- Django框架中处理URLconf中特定的URL的方法