django learning - database operator interface API - (CRUD)

First test API (Interface database operations CRUD)

Now we are entering an interactive python command line, try a variety of API django created for you, open the python command line using the following command:

py -3 manage.py shell into the python command line

 

D:\django\mysite>py -3 manage.py shell

Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32

Type "help", "copyright", "credits" or "license" for more information.

(InteractiveConsole)

 

We use this command instead of simply using "python" because manage.py sets DJANGO_SETTINGS_MODULE environment variable that will be set django python import route packets based on mysite / settings.py file

 

When we successfully entered the command line, to try database API:

Command line initialization model classes and queries:

# Import the model class

>>> from polls.models import Choice, Question

# Query data model class

>>> Question.objects.all()

<QuerySet []>

Question # Create a class object

# In the default configuration file django, time zone, time zones has been activated

#pub_date fields need to zone information (tzinfo) of time to be, so to use timezone.now (), rather than

# Datetiem.datetime.now (), which facilitates the display is switched to the time zone of the time

>>> from django.utils import timezone

>>> q = Question(question_text="What's new?", pub_date=timezone.now())

>>> q.save()

>>> q.id

1

>>> q.question_text

"What's new?"

>>> q.pub_date

datetime.datetime(2019, 10, 4, 10, 4, 45, 113879, tzinfo=<UTC>)

>>> q.pub_text = "What's up?"

>>> q.save()

>>> Question.objects.all()

<QuerySet [<Question: Question object (1)>]>

>>> 

 

<Question: Question object (1)> for our understanding of the details of this object does not help. Let us question by editing the model code (polls / models.py in) to fix this problem.

Question and Choice to increase __str __ () method.

 

Adding to the model __str __ () method

polls/models.py:

 

from django.db import models

# Create your models here.

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

 

Model to increase __str __ () method is very important, not just to give you convenience to use the command line, admin django automatically generated inside also use this method represents an object.

 

Note: These are conventional methods python, let's add a custom method of presentation:

from django.db import models
from django.utils import timezone
import  datetime
# Create your models here.

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

Newly added import datetime from django.utils import timezone and were introduced into the standard django.utils.timezone tool module python django datetime module and the associated time zone.

 

Save the file and then through the p- ython manage.py shell to open the python interactive command line command again:

Query again

>>> from polls.models import Choice, Question

Question # query for all objects classes, see __str __ () is operational

Question.objects.all () query for all objects Question

>>> Question.objects.all()

<QuerySet [<Question: What's new?>]>

 

Question.objects.filter (id = 1) query id of 1

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

<QuerySet [<Question: What's new?>]>

 

Question.objects.filter (question_text__startswith = 'What') What is the query prefix

#startswith front two underscores

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

<QuerySet [<Question: What's new?>]>

 

time zone from django.utils import objects introduced timezone   

>>> from django.utils import timezone

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

>>> current_year

2019

 

Question.objects.get(pub_date__year=current_year)

# Find Published this year's issue

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

<Question: What's new?>

 

Question.objects.get (id = 2) query by id

# Will find no error

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

Traceback (most recent call last):

 …

polls.models.Question.DoesNotExist: Question matching query does not exist.

 

django provide primary key query format pk = 1 Abbreviation

Question.objects.get(pk=1)

#

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

<Question: What's new?>

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

q.was_published_recently () call an instance method

 

>>> q.was_published_recently()

True

q.choice_set.create () to question the relationship between target objects are added choice

We added a few Choice class relation object to the question object.

Method q.choice_set.create create () Constructs a new instance of the object Choice, operations insert statement, adds the instance object to the set of available Choice of choice object and returns a new instance of the object Choice

django will create a collection, the collection of objects to "the other side" Storage foreign key relationships, such as the relationship between the other side of the question object: choice (option), then you can write this relationship through access to database operations API objects

q.choice_set.all () to view the question of the choice option, return QuerySet objects with choice_set, the query can continue to operate

# Choice at the beginning of the relationship between objects is empty

>>> q.choice_set.all()

<QuerySet []>

Create three choice relational object

>>> 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)

c.question View choice object question the relationship between objects

>>> c.question

<Question: What's new?>

# Query again question the object of choice relational object

>>> q.choice_set.all()

<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>

q.choice_set.count () to view the relationship between the number of objects

>>> q.choice_set.count()

3

API will automatically handle relationships as you need, use double underscores to separate relationships, how many layers you want you can have many layers, there is no limit

The following example is to locate the option (choice) corresponding to all the problems, the screening of which is the release date of all the objects in this year's

Reuse current_year variables in the above construction

 

c.delete () delete the object

Choice.objects.filter(question__pub_date__year=current_year)

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

<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>

>>> c = q.choice_set.filter(choice_text__startswith='Just hacking')

>>> c

<QuerySet [<Choice: Just hacking again>]>

>>> c.delete()

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

>>> c

<QuerySet []>

>>> q.choice_set.all()

<QuerySet [<Choice: Not much>, <Choice: The sky>]>

>>> Choice.objects.all()

<QuerySet [<Choice: Not much>, <Choice: The sky>]>

>>> 

 

timezone.now()

>>> timezone.now()

datetime.datetime(2019, 10, 5, 2, 20, 10, 762960, tzinfo=<UTC>)

>>> tz = timezone.now()

tz.year

>>> tz.year

2019

tz.month

>>> tz.month

10

tz.day

>>> tz.day

5

tz.hour

>>> tz.hour

2

tz.minute

>>> tz.minute

20

tz.second

 

>>> tz.second

22

tz.tzinfo

>>> tz.tzinfo

<UTC>

 

Guess you like

Origin www.cnblogs.com/xiaxiaoxu/p/11665817.html