Let’s assume, I have model:
class Media(models.Model):
name = models.Charfield(max_length=20)
type = models.Charfield(max_length=20)
date = models.DateField()
I want that my user should be able to add a field from the frontend.
Like, if user adds a new field from frontend and names it extension.
I want that field to be added in the models.
Thank you!
I think you’re asking for is a dynamic model, you can try by using a generic model that can store any kind of data.
For example:
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
class Media(models.Model):
name = models.CharField(max_length=20)
type = models.CharField(max_length=20)
date = models.DateField()
class MetaData(models.Model):
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
No, maybe you mis-quoted me I want that my user should be able to add a new field of his own choice from the frontend and this field should be stored in my models.
Django does not support this. It is fundamentally contrary to how the Django ORM is architected. Yes, you’ll find answers here and elsewhere showing ways of doing it, but there are a lot of warnings and edge cases that would make any such solution questionable. It’s definitely not recommended trying to do this.
Okay what if we add that field in another model not in that model, how about then.
No.
Django is constructed around the principle that the models exist prior to Django itself being started. It does not support any “dynamic” table modifications. Any changes to any model being used by Django requires that Django be restarted.
(Clarification: By “Django” here, I am specifically referring to the Django ORM. If you’re willing to have your app generate raw SQL to reference those tables, you could build something in Django using a dynamic table structure.)