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

Posted shaomine

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 =[‘[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()

以上是关于Django 学习笔记之五 Django中数据库中ManyToManyField及ForeignKey的主要内容,如果未能解决你的问题,请参考以下文章

简单演示django使用之五--(django概用完结总结篇)

Django 学习笔记之三 数据库输入数据

好程序员分享Python之五分钟了解Django框架设计

Django后端开发学习笔记使用Models并在Django自带管理页面中管理数据

Django后端开发学习笔记使用Models并在Django自带管理页面中管理数据

好程序员Python技术之五分钟了解Django框架设计