dj入门(2)django使用MySql数据库

文章目录

  • 数据库配置(MySQL)
  • 修改时区
  • 创建model
  • 数据库的迁移
  • 如果没有自动创建表,那么可以手动创建
  • ORM基本使用
      • 通过id查询某条记录
  • 写点有用的视图
    • 绑定前端模板
  • 抛出404错误
    • get_object_or_404()

数据库配置(MySQL)

打开 mysite/settings.py 找到以下代码

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

django默认是sqlite3但我们要使用Mysql所有要改成这样

DATABASES = {
    'default': {
        # django数据库引擎
        'ENGINE': 'django.db.backends.mysql',
        # 数据库名
        'NAME': 'polls',
        # 用户名
        'USER': 'root',
        # 登录密码
        'PASSWORD': '123456',
        # 数据库ip
        'HOST': 'localhost',
        # 端口
        'POST': '3306'
    }
}

修改时区

打开 mysite/settings.py 找到 TIME_ZONE 改为你自己的时区 USE_TZ 改为 False

TIME_ZONE = ‘Asia/Shanghai’
USE_TZ = False

创建model

打开 polls/models.py 填写以下代码

from django.db import models


# Create your models here.

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


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=20)
    votes = models.IntegerField(default=0)
  • 每个模型被视为 django.db.models.Model类的子类。每个模型都有许多变量,他们都表示模型里的一个数据库字段
  • 每个字段都是 Field 类的实例,如字符字段表示为 CharField,日期时间字段表示为 DateTimeField。

数据库的迁移

在 mysqit/settings.py 中找到 INSTALLED_APPS并添加 polls 如下所示

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'polls',
]

下载 mysqlclient

pip install mysqlclient

继续执行以下命令

# 检查app下migrations和models是否有更新
python manage.py makemigrations

# 执行修改
python manage.py migrate

如果没有自动创建表,那么可以手动创建

进入polls/models.py

  • 当一个模型位于polls App下名称为Question时,数据库中对应的表名polls_question
  • 我们在model中不设置主键会默认生成一个id作为主键
  • 当我们有ForeignKey时表中字段应该在末尾加上 _id

ORM基本使用

view

from django.http import HttpResponse
from django.utils import timezone

from .models import Question, Choice


def add(request):
    q = Question(question_text="Django", pub_date=timezone.now())
    q.save()
    return HttpResponse("Hello,World.")


url

from django.urls import path

from . import views

urlpatterns = [
    # "www.xxx.com/polls/"
    path('add/', views.add, name="index")
]

view

from django.http import HttpResponse
from django.utils import timezone

from .models import Question, Choice


def select(request):
    question_obj = Question.objects.all()
    print(question_obj)   # , ]>
    return HttpResponse("select")

我们的数据库中如果有两条数据,那么查询出来效果是这样的

, ]>

我们可以在models中重写 __ str __ 方法

class Question(models.Model):
    question_text = models.CharField(max_length=20)
    pub_date = models.DateTimeField("date published")
    objects = models.Manager()  # 防止pycharm views中找不到objects
    
    def __str__(self):
        return self.question_text

这样我们再查询的时候数据就会变成这样

, ]>

url

from django.urls import path

from . import views

urlpatterns = [
    # "www.xxx.com/polls/"
    path('add/', views.add, name="index")
]

通过id查询某条记录

view

# 查(详情)
def detail(request, question_id):
    # question_obj = Question.objects.filter(pk=question_id).first()
    question_obj = Question.objects.get(pk=question_id)
    print(question_obj)
    return HttpResponse(f"detail {question_id}")

url

    path('detail//', views.detail)

写点有用的视图

view

def index(request):
    # 通过pub_date去降序排列,并取出前两个
    latest_question_list = Question.objects.order_by("-pub_date")[:2]
    # 将QuerySet中的数据循环出来填入字符串
    output = ", ".join([q.question_text for q in latest_question_list])
    # 返回字符串
    return HttpResponse(output)

url

    path('index/', views.index, name="index"),

绑定前端模板

创建前端模板

polls/templates/polls/index.html

{% if latest_question_list %}
<ul>
    {% for question in latest_question_list %}
    <li>
        
        

        
        <a href="{% url 'detail' question.id %}">
            {{question.question_text}}
        a>
    li>
    {% endfor%}
ul>
{% else %}
<p> No polls are available.p>
{% endif %}

view

# 查(详情)
def detail(request, question_id):
    # question_obj = Question.objects.filter(pk=question_id).first()
    question_obj = Question.objects.get(pk=question_id)
    return HttpResponse(f"detail {question_obj.question_text}")


def index(request):
    latest_question_list = Question.objects.order_by("-pub_date")[:3]
    # output = ", ".join([q.question_text for q in latest_question_list])
    template = loader.get_template("polls/index.html")
    context = {
        "latest_question_list": latest_question_list
    }
    return HttpResponse(template.render(context, request))
# 这样写更简洁 
#    return render(request, "polls/index.html", context)
    

url

    path('index/', views.index, name="index"),
    path('detail//', views.detail,name="detail")

抛出404错误

def detail(request, question_id):
    # question_obj = Question.objects.filter(pk=question_id).first()
    try:
        question_obj = Question.objects.get(pk=question_id)
    except Question.DoesNotExist:
        raise Http404(f"id为{question_id}的题目不存在")
    return HttpResponse(f"detail {question_obj.question_text}")

get_object_or_404()

需要创建一个detail.html 内容是

<span style="color: red;font-size: 202px">{{question}}span>

view

def detail(request, question_id):
    # question_obj = Question.objects.filter(pk=question_id).first()
    # try:
    #     question = Question.objects.get(pk=question_id)
    # except Question.DoesNotExist:
    #     raise Http404(f"id为{question_id}的题目不存在")

    question = get_object_or_404(Question, pk=question_id)

    context = {
        "question": question
    }

    return render(request, "polls/detail.html", context)
    # return HttpResponse(f"detail {question_obj.question_text}")

你可能感兴趣的:(#,django入门案例,django,数据库,mysql)