Django 的 ORM 有多种关系:一对一,多对一,多对多
各自定义的方式为 :
一对一: OneToOneField (一个有一个,即 has one: OneToOneField)
多对一: ForeignKey (多个属于一个,在建立 ForeignKey 时,另一个表会自动建立对应的关系)
多对多: ManyToManyField (一个既有很多个,又属于很多个,即 has many and belong to : ManyToManyField,同样只能在一个model类中说明,关联表会自动建立。)

多对多关系ManyToManyField
现有三张表,cloud表和project表和Host表,cloud有cloud_type信息,project表中有工程名、cloud_type等信息,host表中有host_name、cloud_type信息;

cloud_type可以属于多个组,一个组中也可以包含多个cloud_type,所以这三个表的关系就是多对多的关系。
models.py代码片段:

#/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible

class Cloud(models.Model):
    cloud_type = models.CharField('主机平台', max_length=256, db_index=True)
    cloud_add_time = models.DateTimeField('更新时间',auto_now_add=True,null=True)
    def __unicode__(self):
        return self.cloud_type
    class Meta:
        verbose_name = '平台架构'
        verbose_name_plural = '平台架构'
        ordering = ['cloud_type']

class Project(models.Model):
    project_name = models.CharField('项目名称', max_length=256)
    cloud = models.ManyToManyField(Cloud, verbose_name='所属平台')
    project_adder = models.CharField('项目地址', max_length=256)
    project_add_time = models.DateTimeField('上线时间',auto_now_add=True,editable=True)
    project_update_time = models.DateTimeField('更新时间',auto_now=True,null=True)
    project_sum = models.IntegerField('更新次数',default=0)

    def __unicode__(self):
        return self.project_name
    def platforms(self):
        return ','.join([i.cloud_type for i in self.cloud.all()])
    class Meta:
        verbose_name = '项目信息'
        verbose_name_plural = '项目信息'
        ordering = ['project_name'] #按项目名称排序

定义platforms函数是为了在后台页面显示cloud_type字段的内容,platforms是后台页面显示的字段名称,
ops/admin.py的内容片段:

#/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
from ops.models import *

class ProjectAdmin(admin.ModelAdmin):
    list_display = ('project_name', 'platforms', 'project_sum', 'project_adder', 'project_add_time', 'project_update_time')
    search_fields = ('project_name', 'project_adder')

class HostAdmin(admin.ModelAdmin):
    list_filter = ('project_host', 'host_virt' , 'host_os')
    list_display = ('project_host', 'host_name', 'host_ip', 'host_eip', 'platforms', 'host_virt', 'host_os', 'host_cpu', 'host_memory', 'host_disk', 'host_app', 'host_port', 'host_status', 'host_add_time', 'host_update_time')
    search_fields = ('project_host','host_name', 'host_ip', 'host_eip', 'host_virt', 'host_os', 'host_disk','host_memory', 'host_app')

class CloudAdmin(admin.ModelAdmin):
    list_display = ('cloud_type', 'cloud_add_time')
    search_fields = ('cloud_type', 'cloud_add_time')

admin.site.register(Project,ProjectAdmin)
admin.site.register(Host,HostAdmin)
admin.site.register(Cloud,CloudAdmin)

后台显示图
admin.jpg

带符号 * 的表示必填项