models.py相關API

models.pypython

import datetime
from django.db import models
from django.utils import timezone

class Question(models.Model):
    def __str__(self):
        return self.question_text

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

    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')


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

 

python shellshell

from polls.models import Choice, Question
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(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)

q.question_text = "What's up?"
q.save()

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?>]>

Question.objects.get(pub_date__year = timezone.now().year) #輸出:<Question: What's up?>
Question.objects.get(id=2)   #輸出:報錯,由於只有1條記錄
Question.objects.get(pk=1)   #輸出:<Question: What's up?>
q = Question.objects.get(pk=1)
q.was_published_recently()   #輸出:True

q = Question.objects.get(pk=1)
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='Just hacking again', votes=0)
c.question   #輸出:<Question: What's up?>
q.choice_set.all()
#輸出:<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
q.choice_set.count() #輸出:3


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.delete()  #刪除該記錄
相關文章
相關標籤/搜索