def creator(**kwargs): # these two are handled automatically - but needed in recursive calls samples = kwargs.get('samples', SAMPLES) parent = kwargs.get('parent', {}) # these are the standard info to pass in model = kwargs.get('model', None) names = kwargs.get('names', []) fields = kwargs.get('fields', []) langs = kwargs.get('langs', []) descendant = kwargs.get('descendant', {}) # order of creation for testing fields_desc = kwargs.get('fields_desc', False) langs_desc = kwargs.get('langs_desc', False) descendant_desc = kwargs.get('descendant_desc', False) # dict sorter function def sorter(x): return x[0] for name in names[:]: info = samples.get(name) if info: names.remove(name) else: continue info = info.copy() for descendant_key, descendant_kwargs in descendant.items(): descendant_kwargs['samples'] = info.pop(descendant_key) translations = info.pop('translations') for parent_key, parent_value in parent.items(): info[parent_key] = parent_value (obj, created) = model.objects.get_or_create(**info) translations_iterable = sorted( translations.items(), key=sorter, reverse=langs_desc ) for lang, dictionary in translations_iterable: if lang in langs: dictionary_iterable = sorted( dictionary.items(), key=sorter, reverse=fields_desc ) for field, text in dictionary_iterable: if field in fields: obj.translations.get_or_create( language=lang, field=field, text=text, ) descendant_iterable = sorted( descendant.items(), key=sorter, reverse=descendant_desc ) for descendant_key, descendant_kwargs in descendant_iterable: parent_key = _get_reverse_relation(model, descendant_key) descendant_kwargs['parent'] = { parent_key: obj } creator(**descendant_kwargs)
def test_invalid_nested_relation(self): with self.assertRaises(FieldDoesNotExist) as error: _get_reverse_relation(Continent, 'countries__wrong') self.assertEqual(error.exception.args[0], "Country has no field named 'wrong'")
def test_nested_reverse_relation(self): self.assertEqual(_get_reverse_relation(City, 'country__continent'), 'countries__cities')
def test_empty_relation(self): with self.assertRaises(FieldDoesNotExist) as error: _get_reverse_relation(Continent, '') self.assertEqual(error.exception.args[0], "Continent has no field named ''")
def test_simple_reverse_relation(self): self.assertEqual(_get_reverse_relation(Country, 'continent'), 'countries')