代码构建模型
class Author(models.Model):
aid = models.AutoField(primary_key=True)
name=models.CharField(max_length=32)
age=models.IntegerField()
# 与AuthorDetail建立一对一的关系
authorDetail=models.OneToOneField(to="AuthorDetail")
class AuthorDetail(models.Model):
did = models.AutoField(primary_key=True)
birthday=models.DateField()
telephone=models.BigIntegerField()
addr=models.CharField(max_length=64)
class Publish(models.Model):
pid = models.AutoField(primary_key=True)
name=models.CharField(max_length=32)
city=models.CharField(max_length=32)
email=models.EmailField()
class Book(models.Model):
bid = models.AutoField(primary_key=True)
title = models.CharField(max_length=32)
publishDate=models.DateField()
price=models.DecimalField(max_digits=5,decimal_places=2)
keepNum=models.IntegerField()<br> commentNum=models.IntegerField()
# 与Publish建立一对多的关系,外键字段建立在多的一方
publish=models.ForeignKey(to="Publish",to_field="pid")
# 与Author表建立多对多的关系,ManyToManyField可以建在两个模型中的任意一个,自动创建第三张表
authors=models.ManyToManyField(to='Author')
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console':{
'level':'DEBUG',
'class':'logging.StreamHandler',
},
},
'loggers': {
'django.db.backends': {
'handlers': ['console'],
'propagate': True,
'level':'DEBUG',
},
}
}
user_types = (
(1, "员工"),
(2, "老板"),
)
identity = models.IntegerField(choices=user_types)
error_messages=None
publish_obj=Publish(name="人民出版社",city="北京",email="[email protected]"
publish_obj.save() # 将数据保存到数据库
publish_obj=Publish.objects.create(name="人民出版社",city="北京",email="[email protected]")
publish_obj=Publish.objects.get(nid=1)
Book.objects.create(title="Django从入门到放弃", publishDate="2012-12-12", price=665, pageNum=334, publish=publish_obj)
book_obj=Book.objects.create(title="Django从入门到放弃",publishDate="2012-12-12",price=665,pageNum=334,publish_id=1)
book_obj=Book.objects.create(title="追风筝的人",publishDate="2012-11-12",price=69,pageNum=314,publish_id=1)
author_yuan=Author.objects.create(name="yuan",age=23,authorDetail_id=1)
author_egon=Author.objects.create(name="egon",age=32,authorDetail_id=2)
book_obj.authors.add(author_egon,author_yuan) # 将某个特定的 model 对象添加到被关联对象集合中。 ======= book_obj.authors.add(*[])
book_obj.authors.create() #创建并保存一个新对象,然后将这个对象加被关联对象的集合中,然后返回这个新对象。
book_obj.authors.remove() # 将某个特定的对象从被关联对象集合中去除。 ====== book_obj.authors.remove(*[])
book_obj.authors.clear() #清空被关联对象集合。
prefetch_related
__iendswith:以指定字符结尾,不区分大小写
models.
Q补充用法
search_fields = ["username", "email"]
query_key = "tom"
condition = Q()
condition.connector = "OR"
for item in search_fields:
condition.children.append(("%s__contains" % item, query_key))
data_list = models.UserInfo.objects.filter(condition)
from django.db import transaction
with transaction.atomic():
sql操作