ORM
创建表(class)
单表
关联表
- 一对一 OneToOne
- 一对多 ForeignKey
- 多对多 ManyToMany
如果存在外键:
- 一对多:
models.Book.objects.create(title="python", price=12, publish_id=2)
models.Book.objects.create(title="python",price=123, publish_objects)
- 多对多;
自动创建表
add() remove()
--->正向查询
book=models.Book.objects.filter(id=3)[0]
author=models.Author.objects.filter(id__gt=2)
book.author.add(*authors)
--->反向查询
author=models.Author.objects.filter(id=2)[0]
books=models.Book.objects.filter(id__gt=2)
author.book_set.add(*books)
手动创建表:
class Book2Author(models.Model):
author=models.ForeignKey("Author")
book=models.ForeignKey("Book")
# 创建联合唯一dd
class Meta:
unique_together=["author", "book"]
操作表:
增
--> create
models.Book.objects.create(title="python",price=123)
dic={title="python",price=123}
models.Book.objects.create(**dic)
--> save
obj=Book(title="python", price=12)
obj.save()
obj=Book()
book.title="go"
book.price=123
obj.save()
删
models.Book.object.filter(id=2).delete() # 级联删除
改
Publisher.objects.filter(id=2).update(name="American publisher")
查
filter all get 三个方法, get返回对象,其他两个返回QuerySet集合
惰性机制: 只用调用时才执行
设置Django logging:
...
__ 双下划线
models.Tb1.objects.filter(id__gt=3)
models.Tb1.objects.filter(id__in=[1,2,3])
models.Tb1.objects.filter(title__contains = "haha")
models.Tb1.objects.filter(title__icontains = "haha")
models.Tb1.objects.filter(title__startwith= "P")
models.Publish.objects.filter(book__title="python").values("name")
models.Book.objects.filter(title="python").values("publisher_name")
聚合查询
--> aggregate
Book.objects.all().aggregate(Avg('price'))
Book.objects.filter(authors__name='alex').aggregate(Sum('price')
分组查询
--> annotate
Book.objects.values("authors__name").annotate(sum('price'))
F查询
models.Book.objects.all().update(price=F("price")+20)
Q查询:封装条件关键字查询
models.Book.objects.filter(Q(id=3)|Q(title="Go"))
admin的配置
python manage.py makemigrations
python mange.py migrate
python manage.py createsuperuser
admin.py
class Myadmin(admin.ModelAdmin):
list_display = ("title", "price", "publisher")
search_fields = ("title", "price")
list_filter = ("title")
ordering = ("-id",)
admin.site.registerI(Book, Myadmin);
配置mysql
settings.py
DATABASE{
'default':{
'ENGINE': 'django.db.backends.mysql',
'NAME': 'ORM',
'HOST': '192.168.12.200',
'PORT': '3306',
'USER': 'root',
'password': '123456',
}
}
__init__.py
import pymysql
pymysql.install_as_MySQLdb()