django-adminstartprojectzqxt

cdzqxt

pythonmanage.pystartappblog

把blog加入到settings.py中的INSTALL_APPS中

blog/models.py

fromdjango.dbimportmodels

classAuthor(models.Model):

name=models.CharField(max_length=50)

qq=models.CharField(max_length=10)

addr=models.TextField()

email=models.EmailField()

def__str__(self):

returnself.name

classArticle(models.Model):

title=models.CharField(max_length=50)

author=models.ForeignKey(Author,on_delete=models.CASCADE)

content=models.TextField()

score=models.IntegerField()#文章的打分

tags=models.ManyToManyField(Tag)

def__str__(self):

returnself.title

classTag(models.Model):

name=models.CharField(max_length=50)

def__str__(self):

returnself.name

假设一篇文章只有一个作者(Author),一个作者可以有多篇文章(Article),一篇文章可以有多个标签(Tag)。

创建migrations然后migrate在数据库中生成相应的表:

pythonmanage.pymakemigrations

pythonmanage.pymigrate

生成一些示例数据,运行initdb.py

importrandom

fromzqxt.wsgiimport*

fromblog.modelsimportAuthor,Article,Tag

author_name_list=[WeizhongTu,twz,dachui,zhe,zhen]

article_title_list=[Django教程,Python教程,HTML教程]

defcreate_authors():

forauthor_nameinauthor_name_list:

author,created=Author.objects.get_or_create(name=author_name)

#随机生成9位数的QQ,

author.qq=.join(

str(random.choice(range(10)))for_inrange(9)

)

author.addr=addr_%s%(random.randrange(1,3))

author.email=%s

ziqiangxuetang.


转载请注明地址:http://www.tanhuaa.com/gyth/10905.html