[Fixed]-How to add new table to database in the Django application

1👍

I don’t think you want to add a new table for every category. Instead, use a Product model with a foreign key to a Category model:

class Category(models.Model):
    name =  models.CharField(max_length=100)

class Product(models.Model):
    name = models.CharField(max_length=100)
    category =  models.ForeignKey(Category, on_delete=models.PROTECT)

This way, adding a new “table” is just a matter of entering a new row in the Category table. If you want to restrict a category to a user then you can add a created_by field on the Category model and base your access logic on it.

Note that on_delete=models.PROTECT on the foreign key means you can’t delete a category as long as there are still products that use that category.

Leave a comment