0

I am looking for a way to achieve the following with Django, would appreciate it if someone can point me in the right direction to do this.

There are 3 registered models in an app (Model1,Model2 and Model3). The user will submit a form (single field, e.g. Project Name and Submit button), let's say the project he creates by submitting this form is 'PROJECT001'. Then what is expected to be done is to copy/clone the 3 models (Model1,Model2 and Model3) with a suffix of the project, i.e. 3 new models should be created 'PROJECT001_Model1', 'PROJECT001_Model2', 'PROJECT001_Model3'.

I have tried to search for this, however can't find any resources. The closest I have found is https://code.djangoproject.com/wiki/DynamicModels but this documentation seems confusing. Any help is appreciated. Thanks.

1 Answer 1

1

If there's no specific reason for cloning your models, I would suggest a different structure here: You could add a project model and create foreign keys on the other three models linking to it. This way you would have instances of Model1, Model2, Model3 specific to individual projects.

from django.db import models

class Project(models.Model):
    pass

class Model1(models.Model):
    project = models.ForeignKey(Project, on_delete=models.CASCADE)

class Model2(models.Model):
    project = models.ForeignKey(Project, on_delete=models.CASCADE)

class Model3(models.Model):
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Soren. This works too but the 3 models in question have a vertical structure i.e. fewer columns and a huge number of rows. I'm worried that it would impact the performance. Do you think my concern is valid?
It really depends on specifics here. Generally, I would argue that having a normalized database is a great advantage in later development. Also, as you already found out, it would be tricky to realize the dynamic creation and management of tables using Django. Lastly, your ForeignKey field will automatically create a database index which should help performance significantly here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.