'Create dynamic model field in Django?

In my models.py my model store contains name, brand_name fields

Now,I want to create new field called brand_type in store model dynamically from Django admin,how can I do this? Can we change schema of model using SchemaEditor? How?



Solution 1:[1]

you can't create model's fields via admin panel

you must create fields in models.py

admin panel is only a convinient way to manipulate your database, but not modifiyng its tables

Solution 2:[2]

It requires migration while the server is running. Create brand_type field under your model and set blank=True

Solution 3:[3]

In your models.py

class Store(models.Model):
    name =  ...
    brand_name = ...
    brand_type = models.CharField(max_length = 40, blank= True, null =true)

In your console

./manage.py makemigrations
./manage.py migrate

Extra Stuff:

If you are interested in Text Choices

or

If you wanna make it more dynamic based on your use case, create a model called BrandType and link it in Store using

brand_type = models.ForeignKey(BrandType,on_delete=models.PROTECT)

models.py

class BrandType(models.Model):
    name = ...
    some_other fields=

#... Store model follows

admin.py

# other stuff
from .models import BrandType
admin.site.register(BrandType)

Take away: It is not advisable to modify your models.py file using admin directly it will cause integrity issues and there are better ways to achieve your desired functionality.

Solution 4:[4]

indentation problem, should return after completing the for loop:

def mode(x):
  y={}
  for a in x:
    if not a in y:
      y[a]=1 
    else:
      y[a]+=1 
  return [g for g,l in y.items() if l==max(y.values())]
print("The mode  of List is", mode(C))

just for completion, there is function mode in the statistics library:

import statistics
C=[13, 15, 16, 19, 20, 20]
statistics.mode(C)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 oruchkin
Solution 2 enes islam
Solution 3
Solution 4