首页 > 代码库 > Django 学习笔记之五 Django中数据库中ManyToManyField及ForeignKey

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

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 =[‘mike@sina.com‘,‘marry@sina.com‘,‘jack@qq.com‘,‘tom@qq.com‘]
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()

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