+class ManyToManyValue(AttributeValue):
+ content_type = models.ForeignKey(ContentType, limit_choices_to=value_content_type_limiter, verbose_name='Value type', null=True, blank=True)
+ values = models.ManyToManyField(ForeignKeyValue, blank=True, null=True)
+
+ def get_object_id_list(self):
+ if not self.values.count():
+ return []
+ else:
+ return self.values.values_list('object_id', flat=True)
+
+ def get_value(self):
+ if self.content_type is None:
+ return None
+
+ return self.content_type.model_class()._default_manager.filter(id__in=self.get_object_id_list())
+
+ def set_value(self, value):
+ # Value is probably a queryset - but allow any iterable.
+
+ # These lines shouldn't be necessary; however, if value is an EmptyQuerySet,
+ # the code won't work without them. Unclear why...
+ if not value:
+ value = []
+
+ if isinstance(value, models.query.QuerySet):
+ value = value.values_list('id', flat=True)
+
+ self.values.filter(~models.Q(object_id__in=value)).delete()
+ current = self.get_object_id_list()
+
+ for v in value:
+ if v in current:
+ continue
+ self.values.create(content_type=self.content_type, object_id=v)
+
+ value = property(get_value, set_value)
+
+ def value_formfield(self, form_class=forms.ModelMultipleChoiceField, **kwargs):
+ if self.content_type is None:
+ return None
+ kwargs.update({'initial': self.get_object_id_list(), 'required': False})
+ return form_class(self.content_type.model_class()._default_manager.all(), **kwargs)
+
+ def apply_data(self, cleaned_data):
+ if 'value' in cleaned_data and cleaned_data['value'] is not None:
+ self.value = cleaned_data['value']
+ else:
+ self.content_type = cleaned_data.get('content_type', None)
+ # If there is no value set in the cleaned data, clear the stored value.
+ self.value = []
+
+ class Meta:
+ app_label = 'philo'