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

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

My python version
>python -V
Python 2.7.13

Install pip
>wget https://bootstrap.pypa.io/get-pip.py
>pip -V
pip 9.0.1 from /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages (python 2.7)

Install django or upgrade django
>pip install django
>pip install -U Django

Check the django version
>python -m django --version
1.11

Install gunicorn
http://docs.gunicorn.org/en/latest/install.html
>pip install gunicorn
>pip install greenlet

Some more related settings are here
http://sillycat.iteye.com/blog/2117576

Create Project according to latest document and My old Blog
>django-admin startproject myconsole
This will create the project myconsole

Running the develop server
>python manage.py migrate
This will apply the database things for the existing modules

>python manage.py runserver

We can visit http://localhost:8000/ after that.

>python manage.py runserver 0:8000
This command will allow 0.0.0.0 to access my service.

Creating the Polls App
>python manage.py startapp polls

Write first view
polls/views.py
# -*- coding: utf-8 -*-from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponse

def index(request):
    return HttpResponse("We are in the index page.")

pools/urls.py
from django.conf.urls import url
from . import views

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

myconsole/urls.py
from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^polls/', include('polls.urls')),
    url(r'^admin/', admin.site.urls),
]

And this URL will open our page
http://localhost:8000/polls/

Go on with Sample https://docs.djangoproject.com/en/1.11/intro/tutorial02/
Creating models
View and check the sqlite3 file
http://sqlitebrowser.org/

polls/models.py
# -*- coding: utf-8 -*-from __future__ import unicode_literals

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)

Add installed apps in  my console/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',
]

>python manage.py makemigrations polls
That will generate the SQL related things.

>python manage.py sqlmigrate polls 0001
This will show your the SQL

Check issues
>python manage.py check
System check identified no issues (0 silenced).

>python manage.py migrate
We will have all the tables setting up.

Enter the shell
>python manage.py shell

Database APIs in the shell
>>> from polls.models import Question, Choice
>>> Question.objects.all();
>>> from django.utils import timezone
>>> q = Question(question_text="what's new?", 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's up?"
>>> q.save()

Add __str__ on the object
def __str__(self):
    return self.question_text
def was_published_recently(self):
    return self.pub_date >= timezone.now() - timezone.timedelta(days=1)


>>> from polls.models import Question, Choice
>>> Question.objects.all()
<QuerySet [<Question: what's up?>]>
>>> Question.objects.filter(id=1)
<QuerySet [<Question: what's up?>]>
>>> Question.objects.filter(question_text__startswith='what')
<QuerySet [<Question: what's up?>]>
>>> from django.utils import timezone
>>> current_year = timezone.now().year
>>> Question.objects.get(pub_date__year=current_year)
<Question: what's up?>
>>> Question.objects.get(id=2)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/query.py", line 379, in get
    self.model._meta.object_name
DoesNotExist: Question matching query does not exist.

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

Create three choices.
>>> q.choice_set.all()
<QuerySet []>
>>> 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='Hacking again', votes=0)
>>> c.question
<Question: what's up?>
>>> q.choice_set.all()
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Hacking again>]>
>>> q.choice_set.count()
3
>>> Choice.objects.filter(question__pub_date__year=current_year)
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Hacking again>]>
>>> c = q.choice_set.filter(choice_text__startswith="Hacking')
  File "<console>", line 1
    c = q.choice_set.filter(choice_text__startswith="Hacking')
>>> c.delete()
(1, {u'polls.Choice': 1})
>>> q.choice_set.all()
<QuerySet [<Choice: Not much>, <Choice: The sky>]>

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

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

Python Lover
http://sillycat.iteye.com/blog/2116834
http://sillycat.iteye.com/blog/2116836
http://sillycat.iteye.com/blog/2117212
http://sillycat.iteye.com/blog/2117576

http://sillycat.iteye.com/blog/2188140
http://sillycat.iteye.com/blog/2243749
http://sillycat.iteye.com/blog/2243775
http://sillycat.iteye.com/blog/2244167
http://sillycat.iteye.com/blog/2244169




猜你喜欢

转载自sillycat.iteye.com/blog/2372912