Article Directory
- Objects created Question
- Question query object created
- __ __ STR () method
- Database lookup API
- Custom method
- Objects created Choice
- [On a: + Django hands introductory tutorial 3- actual database configuration Pycharm] (https://blog.csdn.net/baidu_39459954/article/details/90234659)
- Next: + Django hands-entry Pycharm combat tutorial 5- admin page
Objects created Question
Now let's get into the interactive Python command line, try a variety of API Django created for you. Open Python commands using the following command line:
Python manage.py shell
or we can open Pycharm of Tool-> Python Console
Python 3.7.3 (v3.7.3: ef4ec6ed12, Mar 25 2019, 22:22:05) [the MSC v.1916 'bit 64 (the AMD64)] ON Win32
the Django 2.2.1
Choice and Question introduced model classes we created last article:
>>> from polls.models import Choice, Question
Question of the query, is now empty:
>>> Question.objects.all()
<QuerySet []>
Create a new Question, recommended timezone.now () instead datetime.datetime.now in Django (), so the introduction timezone:
>>> from django.utils import timezone
>>> q = Question(question_text="What's new?", pub_date=timezone.now())
Use save (), save Question into the database just created:
>>> q.save()
Query the database can be seen, the data has been saved:
Question query object created
ID is automatically generated, q.id can query the current id number:
>>> q.id
1
通过python属性访问模型字段值:
Access model field values via Python attributes.
>>> q.question_text
"What's new?"
>>> q.pub_date
datetime.datetime(2019, 5, 19, 16, 23, 13, 320097)
通过修改属性修改对应的值,然后再调用save():
>>> q.question_text = "What's up?"
>>> q.save()
objects.all()显示数据库中所有的对象:
>>> Question.objects.all()
<QuerySet [<Question: Question object (1)>]>
__ str __() 方法
但是输出结果 <Question: Question object (1)> 对于我们了解这个对象的细节没什么帮助。我们可以通过编辑 Question 模型的代码(位于 polls/models.py 中)来修复这个问题。给 Question 和 Choice 增加 __str __() 方法。
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):
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
重新打开Python Console,再次查询,确认我们加的__str __() 生效了:
>>> from polls.models import Choice, Question
>>> Question.objects.all()
<QuerySet [<Question: What's up?>]>
数据库查找API
Django提供了丰富的数据库查找API,它完全由关键字参数驱动。
>>> 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?>
如果请求不存在的ID,将引发异常:
>>> Question.objects.get(id=2)
Traceback (most recent call last):
...
polls.models.Question.DoesNotExist: Question matching query does not exist.
通过主键查找是最常见的情况,因此Django提供了主键精确查找的快捷方式,以下内容与Question.objects.get(id = 1)相同。
>>> Question.objects.get(pk=1)
<Question: What's up?>
自定义方法
给模型增加 __ str__() 方法是很重要的,这不仅仅能给你在命令行里使用带来方便,Django 自动生成的 admin 里也使用这个方法来表示对象。
注意:这些都是常规的 Python方法。让我们添加一个自定义的方法was_published_recently,这只是为了演示:
import datetime
from django.db import models
from django.utils import timezone
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)
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
重新连接,查看我们新加的自定义方法是否生效:
>>> from polls.models import Choice, Question
>>> q = Question.objects.get(pk=1)
>>> q.was_published_recently()
True
创建Choice对象
给提出的问题添加几个选择。
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
(Eg selection problem) can be accessed via the API.
>>> q = Question.objects.get(pk=1)
Q display object (primary key 1) corresponding to the choice, currently empty.
>>> q.choice_set.all()
<QuerySet []>
Create three Choice:
>>> 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 object.
>>> c.question
<Question: What's up?>
And vice versa: Question Choice object can access the object.
>>> q.choice_set.all()
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
>>> q.choice_set.count()
3
API will automatically track the relationship according to your needs, use double underscores to separate relationships, which can be as deep as you want multi-level; there is no limit.
Find pub_date select any problems at all this year (reusable created above us 'current_year' variable).
>>> from django.utils import timezone
>>> current_year = timezone.now().year
>>> Choice.objects.filter(question__pub_date__year=current_year)
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
Use delete () delete a choice.
>>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
>>> c.delete()
Query the database and found that the corresponding choice deleted