[英]Django model custom fields
I want to build Django Model with basic fields and give user the ability to add custom fields from the UI. 我想用基本字段构建Django模型,并让用户能够从UI添加自定义字段。 I thought I can add JSON field because I'm using PostgreSQL so that user can add any number of custom fields as save them as JSON. 我以为可以添加JSON字段,因为我使用的是PostgreSQL,以便用户可以添加任意数量的自定义字段并将其另存为JSON。
I want to ask Is the above approach is correct? 我想问一下以上方法是否正确? or Shall I create another table for custom fields? 还是我应该为自定义字段创建另一个表? Please if there is another approach please guide me to it. 如果还有其他方法,请指导我。
You can create your own widget with custom ui: 您可以使用自定义ui创建自己的小部件:
class JSONWidget(forms.Textarea):
class Media:
js = (
'admin/json-widget/json-widget.js',
)
def render(self, name, value, attrs=None):
if 'class' in attrs:
attrs['class'] += ' json-widget'
else:
attrs['class'] = 'json-widget'
final_attrs = self.build_attrs(attrs, name=name)
return mark_safe(u'<textarea%s>%s</textarea>' % (flatatt(final_attrs),
conditional_escape(force_unicode(value))))
class JSONField(models.TextField):
def formfield(self, **kwargs):
kwargs['widget'] = JSONSWidget()
return super(JSONField, self).formfield(**kwargs)
class SomeModel(model.Model):
jsonfield = JSONField()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.