码迷,mamicode.com
首页 > 数据库 > 详细

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

时间:2016-12-12 20:07:16      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:dom   ack   sel   objects   []   code   timezone   range   tle   

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

标签:dom   ack   sel   objects   []   code   timezone   range   tle   

原文地址:http://www.cnblogs.com/shaosks/p/6165285.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!