fix: actualizacion de categorias en la importacion de productos.
This commit is contained in:
parent
f807137a8e
commit
47098c48af
@ -1,4 +1,4 @@
|
||||
"producto","unidad","precio","categorias"
|
||||
"Aceite","Unidad", 50000,"Aceites&Alimentos"
|
||||
"Café","Unidad", 15000,"Cafes&Alimentos"
|
||||
"Arroz","Unidad", 6000,"Cafes&Alimentos"
|
||||
"Arroz","Unidad", 6000,"Alimentos&Granos"
|
||||
|
|
@ -48,6 +48,21 @@ class TestProducts(TestCase):
|
||||
id_post_updated = Product.objects.get(name='Aceite').id
|
||||
self.assertEqual(id_aceite, id_post_updated)
|
||||
|
||||
def test_update_categories_on_import(self):
|
||||
self._import_csv()
|
||||
first_products = self._get_products()
|
||||
first_categories = {p["name"]: p["categories"] for p in first_products}
|
||||
self._import_csv('example_products2.csv')
|
||||
updated_products = self._get_products()
|
||||
updated_categories = {p["name"]: p["categories"] for p in updated_products}
|
||||
|
||||
self.assertIn('Cafes', first_categories['Arroz'])
|
||||
self.assertNotIn('Granos', first_categories['Arroz'])
|
||||
|
||||
self.assertIn('Granos', updated_categories['Arroz'])
|
||||
self.assertNotIn('Cafes', updated_categories['Arroz'])
|
||||
|
||||
|
||||
def test_update_price(self):
|
||||
self._import_csv()
|
||||
first_products = self._get_products()
|
||||
|
@ -55,6 +55,14 @@ def import_products(request):
|
||||
{'form': form}
|
||||
)
|
||||
|
||||
def _categories_from_csv_string(categories_string, separator="&"):
|
||||
categories = categories_string.split(separator)
|
||||
clean_categories = [c.strip() for c in categories]
|
||||
return [_category_from_name(category) for category in clean_categories]
|
||||
|
||||
def _category_from_name(name):
|
||||
return ProductCategory.objects.get_or_create(name=name)[0]
|
||||
|
||||
def handle_import_products_file(csv_file):
|
||||
data = io.StringIO(csv_file.read().decode('utf-8'))
|
||||
reader = csv.DictReader(data, quotechar='"')
|
||||
@ -63,15 +71,10 @@ def handle_import_products_file(csv_file):
|
||||
name=row['producto'],
|
||||
defaults={
|
||||
'price': row['precio'],
|
||||
'measuring_unit': row['unidad'],
|
||||
'measuring_unit': row['unidad']
|
||||
}
|
||||
)
|
||||
|
||||
categories = [n.strip() for n in row["categorias"].split("&")]
|
||||
categories = _categories_from_csv_string(row["categorias"])
|
||||
product.categories.clear()
|
||||
for category in categories:
|
||||
category_model, _ = ProductCategory.objects.get_or_create(
|
||||
name=category
|
||||
)
|
||||
category_model.save()
|
||||
product.categories.add(category_model)
|
||||
product.save()
|
||||
product.categories.add(category)
|
||||
|
Loading…
Reference in New Issue
Block a user