【主机管理项目】-(models.py(一对多、多对多数据库创建代码))
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models class UserType(models.Model): caption = models.CharField(max_length=32) class User(models.Model): name = models.CharField(max_length=32) age = models.IntegerField() user_type = models.ForeignKey('UserType', to_field='id') class Host(models.Model): envid = models.CharField(max_length=32, db_index=True) ip = models.GenericIPAddressField(protocol='both', max_length=32, db_index=True) port = models.CharField(max_length=32) username = models.CharField(max_length=32) password = models.CharField(max_length=32) item = models.ForeignKey(to='TestItem', to_field='id') class TestItem(models.Model): item = models.CharField(max_length=32) versionNum = models.CharField(max_length=32) class Application(models.Model): name = models.CharField(max_length=32) r = models.ManyToManyField('Host') # 方式一:自定义关系表 class Host(models.Model): nid = models.AutoField(primary_key=True) hostname = models.CharField(max_length=32, db_index=True) ip = models.GenericIPAddressField(protocol="ipv4", db_index=True) port = models.IntegerField() b = models.ForeignKey(to="Business", to_field='id') # 10 class Application(models.Model): name = models.CharField(max_length=32) # 2 class HostToApp(models.Model): hobj = models.ForeignKey(to='Host', to_field='nid') aobj = models.ForeignKey(to='Application', to_field='id') # HostToApp.objects.create(hobj_id=1,aobj_id=2) # 方式二:自动创建关系表 class Host(models.Model): nid = models.AutoField(primary_key=True) hostname = models.CharField(max_length=32, db_index=True) ip = models.GenericIPAddressField(protocol="ipv4", db_index=True) port = models.IntegerField() b = models.ForeignKey(to="Business", to_field='id') # 10 class Application(models.Model): name = models.CharField(max_length=32) r = models.ManyToManyField("Host") # 无法直接对第三张表进行操作 obj = Application.objects.get(id=1) obj.name # 第三张表操作 obj.r.add(1) obj.r.add(2) obj.r.add(2, 3, 4) obj.r.add(*[1, 2, 3, 4]) obj.r.remove(1) obj.r.remove(2, 4) obj.r.remove(*[1, 2, 3]) obj.r.clear() obj.r.set([3, 5, 7]) # 所有相关的主机对象“列表” QuerySet obj.r.all()