Python Console(1)Version Upgrade and Sample Router/ORM

PythonConsole(1)VersionUpgradeandSampleRouter/ORM

Mypythonversion

>python-V

Python2.7.13

Installpip

>wgethttps://bootstrap.pypa.io/get-pip.py

>pip-V

pip9.0.1from/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages(python2.7)

Installdjangoorupgradedjango

>pipinstalldjango

>pipinstall-UDjango

Checkthedjangoversion

>python-mdjango--version

1.11

Installgunicorn

http://docs.gunicorn.org/en/latest/install.html

>pipinstallgunicorn

>pipinstallgreenlet

Somemorerelatedsettingsarehere

CreateProjectaccordingtolatestdocumentandMyoldBlog

>django-adminstartprojectmyconsole

Thiswillcreatetheprojectmyconsole

Runningthedevelopserver

>pythonmanage.pymigrate

Thiswillapplythedatabasethingsfortheexistingmodules

>pythonmanage.pyrunserver

Wecanvisithttp://localhost:8000/afterthat.

>pythonmanage.pyrunserver0:8000

Thiscommandwillallow0.0.0.0toaccessmyservice.

CreatingthePollsApp

>pythonmanage.pystartapppolls

Writefirstview

polls/views.py

#-*-coding:utf-8-*-from__future__importunicode_literals

fromdjango.shortcutsimportrender

fromdjango.httpimportHttpResponse

defindex(request):

returnHttpResponse("Weareintheindexpage.")

pools/urls.py

fromdjango.conf.urlsimporturl

from.importviews

urlpatterns=[

url(r'^$',views.index,name='index'),

]

myconsole/urls.py

fromdjango.conf.urlsimportinclude,url

fromdjango.contribimportadmin

urlpatterns=[

url(r'^polls/',include('polls.urls')),

url(r'^admin/',admin.site.urls),

]

AndthisURLwillopenourpage

http://localhost:8000/polls/

GoonwithSamplehttps://docs.djangoproject.com/en/1.11/intro/tutorial02/

Creatingmodels

Viewandcheckthesqlite3file

http://sqlitebrowser.org/

polls/models.py

#-*-coding:utf-8-*-from__future__importunicode_literals

fromdjango.dbimportmodels

classQuestion(models.Model):

question_text=models.CharField(max_length=200)

pub_date=models.DateTimeField('datepublished')

classChoice(models.Model):

question=models.ForeignKey(Question,on_delete=models.CASCADE)

choice_text=models.CharField(max_length=200)

votes=models.IntegerField(default=0)

Addinstalledappsinmyconsole/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',

]

>pythonmanage.pymakemigrationspolls

ThatwillgeneratetheSQLrelatedthings.

>pythonmanage.pysqlmigratepolls0001

ThiswillshowyourtheSQL

Checkissues

>pythonmanage.pycheck

Systemcheckidentifiednoissues(0silenced).

>pythonmanage.pymigrate

Wewillhaveallthetablessettingup.

Entertheshell

>pythonmanage.pyshell

DatabaseAPIsintheshell

>>>frompolls.modelsimportQuestion,Choice

>>>Question.objects.all();

>>>fromdjango.utilsimporttimezone

>>>q=Question(question_text="what'snew?",pub_date=timezone.now())

>>>q.save()

>>>q.id

1

>>>q.pub_date

datetime.datetime(2017,5,5,21,52,7,152974,tzinfo=<UTC>)

>>>q.question_text="what'sup?"

>>>q.save()

Add__str__ontheobject

def__str__(self):

returnself.question_text

defwas_published_recently(self):

returnself.pub_date>=timezone.now()-timezone.timedelta(days=1)

>>>frompolls.modelsimportQuestion,Choice

>>>Question.objects.all()

<QuerySet[<Question:what'sup?>]>

>>>Question.objects.filter(id=1)

<QuerySet[<Question:what'sup?>]>

>>>Question.objects.filter(question_text__startswith='what')

<QuerySet[<Question:what'sup?>]>

>>>fromdjango.utilsimporttimezone

>>>current_year=timezone.now().year

>>>Question.objects.get(pub_date__year=current_year)

<Question:what'sup?>

>>>Question.objects.get(id=2)

Traceback(mostrecentcalllast):

File"<console>",line1,in<module>

File"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/manager.py",line85,inmanager_method

returngetattr(self.get_queryset(),name)(*args,**kwargs)

File"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/query.py",line379,inget

self.model._meta.object_name

DoesNotExist:Questionmatchingquerydoesnotexist.

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

>>>q.was_published_recently()

True

Createthreechoices.

>>>q.choice_set.all()

<QuerySet[]>

>>>q.choice_set.create(choice_text='Notmuch',votes=0)

<Choice:Notmuch>

>>>q.choice_set.create(choice_text='Thesky',votes=0)

<Choice:Thesky>

>>>c=q.choice_set.create(choice_text='Hackingagain',votes=0)

>>>c.question

<Question:what'sup?>

>>>q.choice_set.all()

<QuerySet[<Choice:Notmuch>,<Choice:Thesky>,<Choice:Hackingagain>]>

>>>q.choice_set.count()

3

>>>Choice.objects.filter(question__pub_date__year=current_year)

<QuerySet[<Choice:Notmuch>,<Choice:Thesky>,<Choice:Hackingagain>]>

>>>c=q.choice_set.filter(choice_text__startswith="Hacking')

File"<console>",line1

c=q.choice_set.filter(choice_text__startswith="Hacking')

>>>c.delete()

(1,{u'polls.Choice':1})

>>>q.choice_set.all()

<QuerySet[<Choice:Notmuch>,<Choice:Thesky>]>

Moredocuments

https://docs.djangoproject.com/en/1.11/topics/db/queries/

References:

https://docs.djangoproject.com/en/1.11/intro/tutorial01/

PythonLover

相关推荐