Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # coding: utf-8
- from __future__ import unicode_literals
- from django.db import models
- from django.db.models.signals import m2m_changed
- class Host(models.Model):
- name = models.CharField(max_length=20)
- isdelete = models.BooleanField(default=False)
- def __unicode__(self):
- return self.name
- class Project(models.Model):
- name = models.CharField(max_length=20)
- host = models.ManyToManyField(Host)
- isdelete = models.BooleanField(default=False)
- def __unicode__(self):
- return self.name
- class Instance(models.Model):
- name = models.CharField(max_length=20)
- project = models.ForeignKey(Project)
- host = models.ManyToManyField(Host)
- isdelete = models.BooleanField(default=False)
- def __unicode__(self):
- return self.name
- def instance_m2m_change(**kwargs):
- instance = kwargs.pop('instance', None)
- host = kwargs.pop('model', None)
- host_id = kwargs.pop('pk_set', None)
- action = kwargs.pop('action', None)
- if action == 'post_add':
- if host_id:
- for i in host_id:
- host_obj = host.objects.get(id=i)
- instance.project.host.add(host_obj)
- if action == 'post_remove':
- if host_id:
- for i in host_id:
- host_obj = host.objects.get(id=i)
- still_has_instance = instance.project.instance_set.filter(host=host_obj)
- if not still_has_instance:
- instance.project.host.remove(host_obj)
- host_obj = host.objects.get(id=i)
- still_has_instance = instance.project.instance_set.filter(host=host_obj)
- class InstanceModule(models.Model):
- name = models.CharField(max_length=20)
- instance = models.ForeignKey(Instance)
- host = models.ManyToManyField(Host)
- isdelete = models.BooleanField(default=False)
- def __unicode__(self):
- return self.name
- def instancemodule_m2m_change(**kwargs):
- instance = kwargs.pop('instance', None)
- host = kwargs.pop('model', None)
- host_id = kwargs.pop('pk_set', None)
- action = kwargs.pop('action', None)
- if action == 'post_add':
- if host_id:
- for i in host_id:
- host_obj = host.objects.get(id=i)
- instance.instance.host.add(host_obj)
- if action == 'post_remove':
- if host_id:
- for i in host_id:
- host_obj = host.objects.get(id=i)
- still_has_instance = instance.instance.instancemodule_set.filter(host=host_obj)
- if not still_has_instance:
- instance.instance.host.remove(host_obj)
- m2m_changed.connect(instance_m2m_change, sender=Instance.host.through)
- m2m_changed.connect(instancemodule_m2m_change, sender=InstanceModule.host.through)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement