Django数据库与模块models

发布时间:2022-06-20 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Django数据库与模块models脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

上一节做到把一个应用加入到项目中,现在再往里面加一个数据库就可以与数据库进行交互了。

Django默认有一个轻量级的数据库叫SQLite,当我们要更换其他的数据库时,则需要绑定数据库,如何绑定?首先打开项目的settings.py,找到里面的DATABASES,将里面的engine、name、password等改为要连接的数据信息就可以了。这就是数据库与项目绑定的基本方法。

 

Models下面来创建模型:

前面说到模型其实就是数据库的布局,也就是要设计那些数据库,那么就有哪些模型。重温一遍:Models里面的类就是表,属性就是字段(列名),而类的一个对象就是表的一行。创建的每一个Models都是Django.db.models.Model的子类,也就是每一个model都要继承自models.Model,而每一个属性(字段)都是Field的实列。如下:

from django.db import models


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

以上就是模型数据库与模型的在项目中的使用方法。好像也挺简单的~~~貌似不难~~~

到这里就搞好一个数据库与模型了,有了模型之后,那我们怎么去使用这个模型呢?也就是我们去使用数据库里面的表,如何给这个表增删改查?

打开pycharm,进入命令行模式,导入项目的模块,像这样:

>>> from polls.models import Choice, Question  # Import the model classes we just wrote.

# No questions are in the system yet.
>>> Question.objects.all()
<QuerySet []>

# Create a new Question.
# Support for time zones is enabled in the default settings file, so
# Django expects a datetime with tzinfo for pub_date. Use timezone.now()
# instead of datetime.datetime.now() and it will do the right thing.
>>> from django.utils import timezone
>>> q = Question(question_text="What's new?", pub_date=timezone.now())

# Save the object into the database. You have to call save() explicitly.
>>> q.save()

# Now it has an ID.
>>> q.id
1

# Access model field values via Python attributes.
>>> q.question_text
"What's new?"
>>> q.pub_date
datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)

# Change values by changing the attributes, then calling save().
>>> q.question_text = "What's up?"
>>> q.save()

# objects.all() displays all the questions in the database.
>>> Question.objects.all()
<QuerySet [<Question: Question object (1)>]>

以上就是对表里面的数据的操作。等一下,这里还有一点比较重要:当我要打印一个对象时,这是打印的是该对象的地址:并不是我们想要的对象的具体数据,那怎么处理这个问题呢?这时我们在对models设计时,在里面多加一个__str__()方法就可以了。像这样:

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

这时当我们再去打印对象时,就是打印出具体的对象的数据了。

 

脚本宝典总结

以上是脚本宝典为你收集整理的Django数据库与模块models全部内容,希望文章能够帮你解决Django数据库与模块models所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:数据库