def __call__(self, data, serializer): """ Performs validation. TODO: this method has do be simplified once `company` field is removed. """ instance = serializer.instance company_has_changed = not instance or ( 'company' in data and data['company'] != instance.company) companies_have_changed = not instance or ('companies' in data and set( data['companies']) != set(instance.companies.all())) contacts_have_changed = not instance or ('contacts' in data and set( data['contacts']) != set(instance.contacts.all())) if not (company_has_changed or companies_have_changed or contacts_have_changed): return combiner = DataCombiner(instance, data) company = combiner.get_value('company') if company_has_changed and company: companies = (company, ) else: companies = combiner.get_value_to_many('companies') contacts = combiner.get_value_to_many('contacts') if any(contact.company not in companies for contact in contacts): raise serializers.ValidationError( 'The interaction contacts must belong to the specified company.', code='inconsistent_contacts_and_company', )
def __call__(self, data=None, order=None): """Validate that all the fields required are set.""" data_combiner = DataCombiner(order, data) meta = order._meta errors = defaultdict(list) # direct required fields for field_name in self.REQUIRED_FIELDS: field = meta.get_field(field_name) if isinstance(field, models.ManyToManyField): value = data_combiner.get_value_to_many(field_name) else: value = data_combiner.get_value(field_name) if not value: errors[field_name] = [self.message] # extra validators extra_errors = self._run_extra_validators(data, order) for field, field_errors in extra_errors.items(): errors[field] += field_errors if errors: raise ValidationError(errors)
def __call__(self, data, serializer): """Performs validation.""" instance = serializer.instance company_has_changed = not instance or ( 'company' in data and data['company'] != instance.company) contacts_have_changed = not instance or ('contacts' in data and set( data['contacts']) != set(instance.contacts.all())) if not (company_has_changed or contacts_have_changed): return combiner = DataCombiner(instance, data) company = combiner.get_value('company') contacts = combiner.get_value_to_many('contacts') if any(contact.company != company for contact in contacts): raise serializers.ValidationError( 'The interaction contacts must belong to the specified company.', code='inconsistent_contacts_and_company', )
def test_get_value_to_many_data(self): """Tests getting a to-many value from update data.""" instance = Mock(field1=MagicMock()) data = {'field1': [123]} data_combiner = DataCombiner(instance, data) assert data_combiner.get_value_to_many('field1') == data['field1']
def test_get_value_to_many_instance(self): """Tests getting a to-many value from an instance.""" instance = Mock(field1=MagicMock()) instance.field1.all.return_value = [123] data_combiner = DataCombiner(instance, None) assert data_combiner.get_value_to_many('field1') == [123]