django-python数据库表操作实例
Posted 1team8
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django-python数据库表操作实例相关的知识,希望对你有一定的参考价值。
关键词
诗歌网站、一对多、表操作基础练习
poem/models.py
from django.db import models
# Create your models here.
class PoetModel(models.Model):
SEX = ((1,'男'),(2,'女')
DYNASTY = ((1,'唐'),(2,'宋'),(3,'元'))
name = models.CharField(max_length=20)
sex = models.IntegerField(choices=SEX, null=False)
dynasty = models.IntegerField(choices=DYNASTY,null=False)
class Meta:
db_table = 't_poet'
def __str__(self):
return self.name
class PoemModel(models.Model):
title = models.CharField(max_length=100)
content = models.CharField(max_length=1000)
style = models.CharField(max_length=1000)
author = models.ForeignKey(Poet, on_delete=models.CASCADE,null=True)
def __str__(self):
return self.title
class Meta:
db_table = 't_poem'
1.添加诗歌
①李白,将进酒,'君不见黄河之水天上来,奔流到海不复回。',[劝酒,浪漫]
②李白,蜀道难,'蜀道之难,难于上青天!',[浪漫]
③杜甫,登高,'无边落木萧萧下,不尽长江滚滚来。',[多愁]
④杜甫,望岳,'会当凌绝顶,一览众山小。',[浪漫]
⑤李清照,寻寻觅觅,'寻寻觅觅,冷冷清清,凄凄惨惨戚戚。',[多愁]
2.根据名称查询诗歌,并查出作者
3.查询某作者的所有诗歌
4.使用两种方式添加诗歌
李白,赠汪伦,'桃花潭水深千尺,不及汪伦送我情。',[劝酒]
#默认诗人已存在PoetModel中
#1
name = PoetModel.objects.get(name="李白")
PoemModel.objects.create(author=name,title="将进酒",content="君不见黄河之水天上来,奔流到海不复回。",style="劝酒,浪漫")
PoemModel.objects.create(author=name,title="蜀道难",content="蜀道难,'蜀道之难,难于上青天!",style="浪漫")
name = PoetModel.objects.get(name="杜甫")
PoemModel.objects.create(author=name,title="登高",content="无边落木萧萧下,不尽长江滚滚来。",style="多愁")
PoemModel.objects.create(author=name,title="望月",content="会当凌绝顶,一览众山小",style="浪漫")
name = PoetModel.objects.get(name="李清照")
Poemmodel.objects.create(author=name,title="寻寻觅觅",content="寻寻觅觅,冷冷清清,凄凄惨惨戚戚。",style="多愁")
#2
p = PoemModel.objects.get(title="诗歌名")
p.author()
#3
name = PoetModel.objects.get(name="作者名")
poem.objects.filter(author=name)
#4
name = PoetModel.objects.get(name="李白")
poem.objects.create(author=name,title="赠汪伦",content="桃花潭水深千尺,不及汪伦送我情。",style="劝酒")
p = poem(author=name,title="赠汪伦",content="桃花潭水深千尺,不及汪伦送我情。",style="劝酒")
以上是关于django-python数据库表操作实例的主要内容,如果未能解决你的问题,请参考以下文章