# coding=utf-8
from django.db import models """
Django数据库关系:
一对一关系:OneToOneField
多对多关系:ManyToManyField
多对一关系:ForeignKey
""" ## One-to-one relationships
class Place(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=80) def __str__(self): # __unicode__ on Python 2
return "%s the place" % self.name class Restaurant(models.Model):
place = models.OneToOneField(Place, primary_key=True)
serves_hot_dogs = models.BooleanField(default=False)
serves_pizza = models.BooleanField(default=False) def __str__(self): # __unicode__ on Python 2
return "%s the restaurant" % self.place.name ## CREATE TABLE `db_place` (
## `id` int(11) NOT NULL AUTO_INCREMENT,
## `name` varchar(50) NOT NULL,
## `address` varchar(80) NOT NULL,
## PRIMARY KEY (`id`)
## ) ENGINE=InnoDB DEFAULT CHARSET=utf8
##
## CREATE TABLE `db_restaurant` (
## `place_id` int(11) NOT NULL,
## `serves_hot_dogs` tinyint(1) NOT NULL,
## `serves_pizza` tinyint(1) NOT NULL,
## PRIMARY KEY (`place_id`),
## CONSTRAINT `db_restaurant_place_id_606d40e1_fk_db_place_id` FOREIGN KEY (`place_id`) REFERENCES `db_place` (`id`)
## ) ENGINE=InnoDB DEFAULT CHARSET=utf8 class Waiter(models.Model):
restaurant = models.ForeignKey(Restaurant)
name = models.CharField(max_length=50) def __str__(self): # __unicode__ on Python 2
return "%s the waiter at %s" % (self.name, self.restaurant) # CREATE TABLE `db_waiter` (
# `id` int(11) NOT NULL AUTO_INCREMENT,
# `name` varchar(50) NOT NULL,
# `restaurant_id` int(11) NOT NULL,
# PRIMARY KEY (`id`),
# KEY `db_waiter_ee9d9d3e` (`restaurant_id`),
# CONSTRAINT `db_waiter_restaurant_id_7b6c7331_fk_db_restaurant_place_id` FOREIGN KEY (`restaurant_id`) REFERENCES `db_restaurant` (`place_id`)
# ) ENGINE=InnoDB DEFAULT CHARSET=utf8
#
# >python manage.py syncdb
# Operations to perform:
# Apply all migrations: admin, contenttypes, auth, sessions
# Running migrations:
# Applying contenttypes.0001_initial... OK
# Applying auth.0001_initial... OK
# Applying admin.0001_initial... OK
# Applying sessions.0001_initial... OK
#
# You have installed Django's auth system, and don't have any superusers defined.
# Would you like to create one now? (yes/no): yes
# Username (leave blank to use 'zhangsan'): admin
# Email address: admin@admin.com
# Password:*****
# Password (again):*****
# Superuser created successfully.
#
# >python manage.py makemigrations
# Migrations for 'db':
# 0001_initial.py:
# - Create model Place
# - Create model Restaurant
# - Create model Waiter
#
# >python manage.py migrate
# Operations to perform:
# Apply all migrations: admin, contenttypes, db, auth, sessions
# Running migrations:
# Applying db.0001_initial... OK ## Many-to-many relationships
class Publication(models.Model):
title = models.CharField(max_length=30) def __str__(self): # __unicode__ on Python 2
return self.title class Meta:
ordering = ('title',) class Article(models.Model):
headline = models.CharField(max_length=100)
publications = models.ManyToManyField(Publication) def __str__(self): # __unicode__ on Python 2
return self.headline class Meta:
ordering = ('headline',) ## CREATE TABLE `db_publication` (
## `id` int(11) NOT NULL AUTO_INCREMENT,
## `title` varchar(30) NOT NULL,
## PRIMARY KEY (`id`)
## ) ENGINE=InnoDB DEFAULT CHARSET=utf8
##
##
## CREATE TABLE `db_article` (
## `id` int(11) NOT NULL AUTO_INCREMENT,
## `headline` varchar(100) NOT NULL,
## PRIMARY KEY (`id`)
## ) ENGINE=InnoDB DEFAULT CHARSET=utf8
##
## CREATE TABLE `db_article_publications` (
## `id` int(11) NOT NULL AUTO_INCREMENT,
## `article_id` int(11) NOT NULL,
## `publication_id` int(11) NOT NULL,
## PRIMARY KEY (`id`),
## UNIQUE KEY `article_id` (`article_id`,`publication_id`),
## KEY `db_article_publications_a00c1b00` (`article_id`),
## KEY `db_article_publications_72ef6487` (`publication_id`),
## CONSTRAINT `db_article_publicat_publication_id_407fcd4d_fk_db_publication_id` FOREIGN KEY (`publication_id`) REFERENCES `db_publication` (`id`),
## CONSTRAINT `db_article_publications_article_id_b757f51_fk_db_article_id` FOREIGN KEY (`article_id`) REFERENCES `db_article` (`id`)
## ) ENGINE=InnoDB DEFAULT CHARSET=utf8 # >python manage.py makemigrations
# Migrations for 'db':
# 0002_auto_20141013_1311.py:
# - Create model Article
# - Create model Publication
# - Add field publications to article
#
# >python manage.py migrate
# Operations to perform:
# Apply all migrations: admin, contenttypes, db, auth, sessions
# Running migrations:
# Applying db.0002_auto_20141013_1311... OK ## Many-to-one relationships
class Reporter(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField() def __str__(self): # __unicode__ on Python 2
return "%s %s" % (self.first_name, self.last_name) class Articler(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateField()
reporter = models.ForeignKey(Reporter) def __str__(self): # __unicode__ on Python 2
return self.headline class Meta:
ordering = ('headline',) ## CREATE TABLE `db_reporter` (
## `id` int(11) NOT NULL AUTO_INCREMENT,
## `first_name` varchar(30) NOT NULL,
## `last_name` varchar(30) NOT NULL,
## `email` varchar(75) NOT NULL,
## PRIMARY KEY (`id`)
## ) ENGINE=InnoDB DEFAULT CHARSET=utf8
##
## CREATE TABLE `db_articler` (
## `id` int(11) NOT NULL AUTO_INCREMENT,
## `headline` varchar(100) NOT NULL,
## `pub_date` date NOT NULL,
## `reporter_id` int(11) NOT NULL,
## PRIMARY KEY (`id`),
## KEY `db_articler_947bdf92` (`reporter_id`),
## CONSTRAINT `db_articler_reporter_id_26a49a33_fk_db_reporter_id` FOREIGN KEY (`reporter_id`) REFERENCES `db_reporter` (`id`)
## ) ENGINE=InnoDB DEFAULT CHARSET=utf8 # >python manage.py makemigrations
# Migrations for 'db':
# 0003_auto_20141013_1318.py:
# - Create model Articler
# - Create model Reporter
# - Add field reporter to articler
#
# >python manage.py migrate
# Operations to perform:
# Apply all migrations: admin, contenttypes, db, auth, sessions
# Running migrations:
# Applying db.0003_auto_20141013_1318... OK

  源码下载:http://git.oschina.net/gitlab/StartWithCoding/tree/master/example/django/django_db_relationships

Django db relationship的更多相关文章

  1. 在django项目外,使用django.db链接数据库(postgres)

    要用python链接到数据库,又不想写太多代码.想到了django,就偷懒了下.用django.db直连. django版本:1.6.5 (1.5以后可以用以下代码) #coding=utf-8 __ ...

  2. django - from django.db.models import F - class F

    F() 的执行不经过 python解释器,不经过本机内存,是生成 SQL语句的执行. # Tintin filed a news story! reporter = Reporters.objects ...

  3. django: db - display

    本讲介绍数据在页面中的呈现,内容很简单,就是嵌套循环在模板中的使用. 一,修改 csvt03/urls.py: from django.conf.urls import patterns, inclu ...

  4. django: db - admin

    本讲演示简单使用 Django Admin 功能. 一,修改 settings.py,添加 admin 应用: INSTALLED_APPS = ( 'django.contrib.auth', 'd ...

  5. django: db - many to one

    models 模块中的对象有三种对应关系:多对一,多对多,一对一.本讲说明多对一关系. blog/models.py: from django.db import models class Emplo ...

  6. django: db howto - 2

    继 django: db howto - 1 : 一 操作数据库的三种方式: [root@bogon csvt03]# python2.7 manage.py shell Python 2.7.5 ( ...

  7. django: db howto - 1

    以在 Django 中使用 MySQL 为例,首先要安装 MySQL 和 MySQL-python 组件,确保 python 能执行 import MySQLdb. MySQL 中创建数据库: [ro ...

  8. django.db.utils.OperationalError: 1050解决方案

    manage.py migrate时进行同步数据库时出现问题;django.db.utils.OperationalError: (1050, "Table '表名' already exi ...

  9. 报错django.db.migrations.exceptions.InconsistentMigrationHistory

    Pycharm强大的功能总是让我很是着迷,比如它的makemigrations 和 migrate. 然而某一次,当我再次敲下这熟悉的命令时,它报错了.... Traceback (most rece ...

随机推荐

  1. ngnix 配置

    #运行用户 user www-data;     #启动进程,通常设置成和cpu的数量相等 worker_processes  1; #全局错误日志及PID文件 error_log  /var/log ...

  2. 解决wix生成的msi的license对话框空白的问题

    今天用Wix做之前写的那个Windows Live Writer的Markdown插件的msi安装包,在wxs文件中用如下的代码添加license文件,结果发现生成msi后license文件框一直是空 ...

  3. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(47)-工作流设计-补充

    原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(47)-工作流设计-补充 系列目录 补充一下,有人要表单的代码,这个用代码生成器生成表Flow_Form表 ...

  4. ※C++随笔※=>☆C++基础☆=>※№→C++中 #include<>与#include""

    #include<> 使用尖括号表示在包含文件目录中去查找(包含目录是由用户在设置环境时设置的),而不在源文件目录去查找: #include"" 使用双引号则表示首先在 ...

  5. 在32位Windows 8或Windows 7上安装Windows Phone 8 SDK

    这需要一点技巧的,其实WPSDK8是支持32位系统的,可因为微软脑残的限制,安装方法如下: 这里必需要有一个工具,OllyDbg 2.0,去官网下载即可. 启动OD,在菜单打开选项窗口,在Events ...

  6. IO之流程与buffer 图

    http://blog.chinaunix.net/uid-29075379-id-3944364.html

  7. iOS开发--通过MultipeerConnectivity完成蓝牙通讯

    iOS开发–通过MultipeerConnectivity完成蓝牙通讯 iOS蓝牙通讯的三种方式: GameKit.framework:iOS7之前的蓝牙通讯框架,从iOS7开始过期,但是目前已经被淘 ...

  8. ios中从相册:相机中获取图片信息

    ios中从相册/相机中获取图片信息 从相册中获取图片的信息 UIImagePickerController *imgPickView = [[UIImagePickerController alloc ...

  9. ip、数字的互转

    # ip ==> 数字 >>> ip2num = lambda x:sum([256**j*int(i) for j,i in enumerate(x.split('.')[: ...

  10. 谁是谁的first-child

    看过CSS伪类选择器之后,心想也就如此嘛,:first-child选择元素的第一个子元素,有什么难的,可一到实践中,还是到处碰壁啊. <body> <ul class="f ...