发布网友 发布时间:2022-05-01 11:15
共2个回答
懂视网 时间:2022-05-01 15:36
1.在pyCharm中终端执行如下命令创建app
python manage.py startapp books
2. 在models.py中编写模型代码
from django.db import models # Create your models here. class Publisher(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=50) city = models.CharField(max_length=60) state_province = models.CharField(max_length=30) country = models.CharField(max_length=50) website = models.URLField() def __unicode__(self): return self.name class Meta: ordering = [‘name‘] class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40) email = models.EmailField() def __unicode__(self): return ‘%s %s‘ % (self.first_name, self.last_name) class Book(models.Model): title = models.CharField(max_length=100) author = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher) publication_date = models.DateField() def __unicode__(self): return self.title
备注: class Meta表示模型的元信息,eg. 缺省排序; __unicode__方法可以进行任何处理来返回一个对象的字符串表示,类似java中的toString()
3. 校验模型的合法性--语法和逻辑是否正确
python manage.py validate
4. 打印出sql(可以查看django模型与建表sql的对应关系)
python manage.py sqlall books
此时数据库并没有创建任何表
5. 创建表
python manage.py syncdb
6. 登录数据库命令行客户端
python manage.py dbshell (django根据配置文件中配置的数据库信息,自动检测使用不同的命令行客户端)
#########################################################################
如何利用django提供的API进行CRUD操作呢?
1. 创建对象
p1 = Publisher(name="O‘Reilly", address=‘10 Fawcett St.‘, city=‘Cambridge‘, state_province=‘MA‘, country=‘U.S.A.‘, website=‘http://www.oreilly.com/‘) p1.save()
p2 = Publisher.objects.create(name="O‘Reilly", address=‘10 Fawcett St.‘, city=‘Cambridge‘, state_province=‘MA‘, country=‘U.S.A.‘, website=‘http://www.oreilly.com/‘)
2. 查询对象
publisher_list = Publisher.objects.all() #返回querySet,一个伪列表对象 publisher_list = Publisher.objects.filter(name=‘Jerry‘) #此处精确匹配name publisher_list = Publisher.objects.filter(name__contains=‘Jerry‘) #此处模糊匹配name publisher_list = Publisher.objects.filter(name__contains=‘Jerry‘).order_by(‘name‘) #按字母表正向排序 publisher_list = Publisher.objects.filter(name__contains=‘Jerry‘).order_by(‘-name‘) #按字母表逆向排序 publisher = Publisher.objects.get(name=‘Jerry‘) #返回单个对象,此方法会抛出异常,Publisher.DoesNotExist、MultipleObjectsReturned
3. 更新对象
p1 = Publisher(name="O‘Reilly", address=‘10 Fawcett St.‘, city=‘Cambridge‘, state_province=‘MA‘, country=‘U.S.A.‘, website=‘http://www.oreilly.com/‘) p1.save() p1.name=‘update name‘ p1.save() #此方法会更新所有字段,影响性能并且可能会引发竞态条件 Publisher.objects.filter(id=52).update(name=‘Apress Publishing‘) #此方法只更新指定字段,可以有多个参数
4. 删除对象
p = Publisher.objects.get(name="O‘Reilly") p.delete() Publisher.objects.all() Publisher.objects.all().delete() #谨慎使用
django数据库模型
标签:
热心网友 时间:2022-05-01 12:44
null: