在Django中创建动态模型字段?

发布于 2025-01-30 11:23:35 字数 123 浏览 3 评论 0原文

在我的型号中,我的模型商店包含名称,

现在是brand_name字段,我想从Django Admin动态创建名为brand_type的新字段,该字段如何,我该如何执行此操作? 我们可以使用模型架构更改模型模型吗?如何?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦幻之岛 2025-02-06 11:23:35

您无法通过管理面板创建模型字段,

必须型号中创建字段

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

未蓝澄海的烟 2025-02-06 11:23:35

服务器运行时需要迁移。创建brand_type在模型下的字段,并设置空白= true

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

云淡风轻 2025-02-06 11:23:35

在您的

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

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

models.py.py

-types“ rel =” nofollow noreferrer”>文本选择

或者

如果您想根据用例,请更 dynamic
创建一个称为brandType的模型,然后将其链接在store使用

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)

带走:不建议使用admin直接修改models.py文件,这将导致完整性问题,并且有更好的方法可以实现您所需的功能。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文