一、模型

模型类

  1. from django.db import models
  2. class Book(models.Model):
  3. # 必须要指定最大长度
  4. name = models.CharField(max_length=20, null=False)
  5. author = models.CharField(max_length=20, null=False)
  6. price = models.FloatField(default=0)

手动添加数据

image.png

日志

想打印orm对应的sql,在settings中配置:

  1. LOGGING = {
  2. 'version': 1,
  3. 'disable_existing_loggers': False,
  4. 'handlers': {
  5. 'console':{
  6. 'level':'DEBUG',
  7. 'class':'logging.StreamHandler',
  8. },
  9. },
  10. 'loggers': {
  11. 'django.db.backends': {
  12. 'handlers': ['console'],
  13. 'propagate': True,
  14. 'level':'DEBUG',
  15. },
  16. }
  17. }

二、查询

Book.objects.filter 如果没有查询到任何结果,返回空<QuerySet []>
Book.objects.get如果没有查询到任何结果,报异常Internal Server Error,返回类型 QuerySet

1.根据主键进行查找

book = Book.objects.get(pk=1)
book = Book.objects.get(id=1)
print(book)

2.根据其他条件来查找

book = Book.objects.get(author='ecithy')

3.查询所有

book = Book.objects.all()

三、增加

1.create

Book.objects.create(name=name, author=author)

2.save

Book(name=name, author=author).save()
或者

  1. book.name = name
  2. book.author = author
  3. book.price = price
  4. book.save()

四、删除数据

  • 删除queryset

Book.objects.filter(pk>1).delete()

  • 删除model对象

Book.objects.get(pk=1).delete()

五、修改数据

1.update

更新queryset

  1. Book.objects.filter(id=1).update(name='mufengsir')

2.save

更新model对象

  1. book = Book.objects.get(pk=2)
  2. book.price = 200
  3. book.save()