Django 学习笔记之五 Django中数据库中ManyToManyField及ForeignKey分析

你猜 阅读:211 2021-05-27 13:16:20 评论:0

1、model里面的代码:

from __future__ import unicode_literals
import django.utils.timezone as timezone
from django.db import models

# Create your models here.
class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=30)
city = models.CharField(max_length=30)

def __unicode__(self):
return self.name

class Author(models.Model):
name = models.CharField(max_length=30)
email = models.EmailField()

def __unicode__(self):
return self.name

class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication = models.DateField(default=timezone.now())

def __unicode__(self):
return self.title

2、把数据写入数据库(sqlite)

#coding:utf-8
from django_book.wsgi import *
from book.models import Author,Book,Publisher
import datetime
import random

#初始化作者数据
def InitAuthor():
namelist = ['mike','marry','jack','tom']
emaillist =['[email protected]','[email protected]','[email protected]','[email protected]']
autherList = []
for i in range(len(namelist)):
name = namelist[i];
email = emaillist[i]
auther = Author(name=name,email=email)
autherList.append(auther)
Author.objects.bulk_create(autherList)

#初始化出版社数据
def InitPublisher():
namelist = ['shanghaipublisher', 'beijingpublisher', 'beishidapublisher', 'qinghuapublisher']
citylist = ['shanghai', 'beijing', 'beijing', 'beijing']
addresslist = ['shanghai_address', 'beijing_address', 'beijing_address', 'beijing_address']
publisherlist = []
for i in range(len(namelist)):
name = namelist[i];
city = citylist[i]
address = addresslist[i]
publisher = Publisher(name=name, city=city,address=address)
publisherlist.append(publisher)
Publisher.objects.bulk_create(publisherlist)

#初始化书数据
def InitBook():
booklist = ['python','html','django','java']
publisherList = list(Publisher.objects.all())
authorList = list(Author.objects.all())
for i in range(len(booklist)):
title = booklist[i];
publisher = publisherList[i]
book, created =Book.objects.get_or_create(title=title,publisher=publisher,
publication=datetime.datetime.now())
book.author.add(authorList[i])

def DeleteBook():
bobj = Book.objects.all()
bobj.delete()


def main():
# DeleteBook();
# InitAuthor()
# InitPublisher()
InitBook()

if __name__ == '__main__':
main()

标签:Python
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

发表评论
搜索
KIKK导航

KIKK导航

排行榜
关注我们

一个IT知识分享的公众号