0

This is my Django code for my model I want to have columns in the model based on the value of chart type enter column there`

class DashboardCreativeQuery(models.Model):
query_name = models.CharField(max_length=256, null=False, unique=True)
query = models.TextField( null=False)
chart_type = models.ForeignKey(DashboardCreativeCharts, blank=True, null=True, related_name='chart_type',
                           on_delete=models.CASCADE)
if chart_type:
    test=  JSONField(null=False)

How can I do it?

  • I'm not sure to understand what you want to do? Would you like to create dynamic column in your database based on user input? – Raida Mar 29 '22 at 09:39
  • Yes thats right,i want to create dynamic column in your database based on user input? – Kunal Agarwal Mar 29 '22 at 10:06
  • Take a look to that [post](https://stackoverflow.com/questions/7933596/django-dynamic-model-fields) and to this [extension](https://pypi.org/project/django-dcolumns/) – Raida Mar 29 '22 at 11:37

1 Answers1

0

By default, django, uses a Relational Database. A Relational Database store data in relations:

A relation is defined as a set of tuples that have the same attributes.

That means, in a relation (table) all tulles (rows) must have the same attributes (columns). For this reason, if you are using a relation (a table) to store your data, you should don't change model fields dynamically.

What can you do

  • Take a look to django model inheritance, maybe it is a solution for you.
  • Move your solution to a no-sql backend like mongo.
dani herrera
  • 48,760
  • 8
  • 117
  • 177