Django之orm操作数据库(一对多)

models.py 中的内容

from django.db import models
import datetime
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

Python Console中的查询操作:

from polls.models import Choice, Question
from datetime import date
q = Question()
q.pub_date(date(2000,1,1))

q.pub_date = date(2001,1,1)
q.question_text = '我是问题5'
q.save()

q.pub_date
datetime.date(2001, 1, 1)
Question.objects.all()
<QuerySet [<Question: 问题1>, <Question: 问题2>, <Question: 问题三>, <Question: 我是第四个问题>, <Question: 我是问题5>]>
c = Choice()
c.question = q # 用外键属性关联上面生成的Question对象
c.choice_text = '我是答案6'
c.votes = 3
c.save()
c.votes
3
Choice.objects.all()
<QuerySet [<Choice: 答案1>, <Choice: 答案2>, <Choice: 答案3>, <Choice: 我是选项1>, <Choice: 我是答案6>]>
# 用多表查询一表
Choice.objects.get(pk = 5)
<Choice: 我是答案6>
Choice.objects.get(pk = 5).question
<Question: 我是问题5>
Choice.objects.get(pk = 5).question.pub_date
datetime.datetime(2000, 12, 31, 16, 0, tzinfo=<UTC>)
# 从一查询多
q.choice_set.all()
<QuerySet [<Choice: 我是答案6>]>


数据库中对应的表

猜你喜欢

转载自www.cnblogs.com/python99/p/12530503.html
今日推荐