问题描述
有没有办法在Django中创建私有字段.我希望只能通过此类的方法访问此字段.
Is there any way, to create a private field in Django. I want this field be accessible only from this class's methods.
以下是我想要的示例:
class TestModel(models.Model):
__some_field = models.CharField(max_length=255)
解决方案:
更新:最后,我为这种情况设计了自己的解决方案,并将其添加到我的django-fields程序包中,该程序包可在GitHub上找到: https://github.com/svetlyak40wt/django-fields
SOLUTION FOUND:
Update: finally, I forge my own solution for this case and added it into my django-fields package, which is available on the GitHub: https://github.com/svetlyak40wt/django-fields
具体来说,如果要在模型中包含私有字段,则必须从我的 ModelWithPrivateFields 类.
Specifically, if you want to have private fields in your models, then you have to inherit them from my ModelWithPrivateFields class.
推荐答案
为什么要这样做?
如果您只想在管理界面中隐藏此字段,则可以使用该字段的名称而不必使用下划线(据我所知,这对Django没什么影响)并注册TestModelAdmin类:
If you just want to hide this field in admin interface you can use name of this field without leading underscore (it doesn't make any difference for Django, as far as I know) and register TestModelAdmin class:
class TestModelAdmin(admin.ModelAdmin):
exclude = ('some_field',)
admin.site.register(TestModel, TestModelAdmin)
这篇关于如何在Django中创建私有模型字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!