建立数据库模型

bigzhu posted @ Jul 02, 2007 06:39:00 PM in django , 1448 阅读

建立模型,首先必须先建立一个app

一个app是Django的可移动功能集,可以使用更大一层的project的配置,有点像java的jar包

在刚才成功配置了数据库连接的project下执行

python manage.py startapp books

建立了一个名为books的app

编辑app下的models.py,写入想要建立的模型,比如:

class Publisher(models.Model):
name = models.CharField(maxlength=30)
address = models.CharField(maxlength=50)
city = models.CharField(maxlength=60)
state_province = models.CharField(maxlength=30)
country = models.CharField(maxlength=50)
website = models.URLField()

class Author(models.Model):
salutation = models.CharField(maxlength=10)
first_name = models.CharField(maxlength=30)
last_name = models.CharField(maxlength=40)
email = models.EmailField()
headshot = models.ImageField(upload_to='/tmp')

class Book(models.Model):
title = models.CharField(maxlength=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication_date = models.DateField()

熟悉数据库的一看就懂…这里不罗嗦了.

编辑settings.py,激活app books,虽然建立了app,但是出于安全的考虑,并没有将其激活.

tuple INSTALLED_APPS中加入’mysite.books’

验证模型的逻辑结构:

在project下输入

python manage.py validate

来验证.

现在可以让django来根据模型生成sql语句了.输入:

python manage.py sqlall books

可以看到输出的sql语句.

可以取得这些sql,自己到数据库上执行,生成表

也可以使用

python manage.py syncdb

来通过django把sql提交给数据库.


pavzi.com 说:
Jan 10, 2024 10:47:22 AM

The primary idea or goal of this website has been to offer resources that contain comprehensive information on every subject and are accessible via the Internet. making certain that each and every reader finds the most relevant and pavzi.com worthwhile information regarding the subject they are searching for and linking to our content.Because our website is multi-niche or multi-category, it will guarantee that it offers resources and information on every subject. Our website features a number of timeless topics, including career, job recruitment, education, technology, and reviews, among others. Indeed, Tech, Finance, and Product Reviews are our primary focus.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter