Converting texts to foreign keys when importing data with Django excel

59 Views Asked by At

Tbl.1

id author brand_id name barcode unit
user1 TestBrand1 Product1 TST1234 700
user2 TestBrand2 Product2 TST5678 380

I have an excel spreadsheet as in the example above. The author and brand_id in the table fields represent the foreignkey fields in the model.

When the user wants to add a product to the system with excel, he/she has to enter the author and the brand as strings. Like the table in the example above.

But since author and brand_id are foreign keys, excel should be like this.`

Tbl.2

id author brand_id name barcode unit
1 1 Product1 TST1234 700
2 2 Product2 TST5678 380

My question is how can I dynamically convert the author and brand data received as strings as a foreign key on the database and save it.

For example, if brand_id = TestBrand1, I want to record the id of that brand on the database.(As in Tbl.2)

Here my Product models:

class Product(models.Model):
id = models.AutoField(primary_key=True)
author = models.ForeignKey(User,on_delete= models.CASCADE, verbose_name='Product Author', null=True)
brand_id = models.ForeignKey(Brand,on_delete=models.CASCADE, verbose_name="Brand Names")
name = models.CharField(max_length=255, verbose_name="Product Name",unique=True)
barcode = models.CharField(max_length=255, verbose_name="Barcode")
unit = models.CharField(max_length=255,verbose_name="Product Unit") 

def __str__(self):
    return self.name

Here my product views:

@login_required(login_url="login")
def addProduct(request):
    . 
    .
    .
    .
    .
        elif 'save_file' in request.POST:
            dataset = Dataset()
            new_products = request.FILES['product_file']
            if not new_products.name.endswith('xlsx'):
                messages.info(request,'Wrong file format!')
                return redirect(".")

            imported_data = dataset.load(new_products.read(), format='xlsx')
            for data in imported_data:
                values = Product(
                    data[0],
                    data[1],
                    data[2],
                    data[3],
                    data[4],
                    data[5],
                )
                values.save()
            messages.success(request,"Product added from file succesfully!")
            return redirect("products")
                
    context = {
        .
        .
        .
        .
    }
    return render(request,"product/addproduct.html",context)

Thank you for your help, best regards

1

There are 1 best solutions below

2
On BEST ANSWER

Since I couldn't find a method for this, I solved it in a hardcoing way.