如何在Django模型中存储任意的名称/值密钥对? [英] How to store arbitrary name/value key pairs in a Django model?

查看:109
本文介绍了如何在Django模型中存储任意的名称/值密钥对?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个固定的数据模型,有很多数据字段。

I have a fixed data model that has a lot of data fields.


class Widget(Models.model):
    widget_owner = models.ForeignKey(auth.User)
    val1 = models.CharField()
    val2 = models.CharField()
    ...
    val568 = ...

我想通过让我的用户指定自定义数据字段来填补这个Widget中的更多数据。什么是一个理智的方法呢?存储名称/值对在哪里用户可以指定其他小部件字段一个好主意?我的伪想法如下:

I want to cram even more data into this Widget by letting my users specify custom data fields. What's a sane way to do this? Is storing name/value pairs where the user can specify additional "Widget fields" a good idea? My pseudo thoughts are below:


data_types = ('free_text', 'date', 'integer', 'price')
class CustomWidgetField(models.Model)
  owner = ForeignKey(auth.User)
  field_title = models.CharField(auth.User)
  field_value_type = models.CharField(choices = data_types)

class CustomWidgetValue(models.Model)
  field_type = ForeignKey(CustomWidgetField)
  widget = ForeignKey(Widget)
  value = models.TextField()
So I want to let each user build a new type of data field that will apply to all of their widgets and then specify values for each custom field in each widget.  I will probably have to do filtering/searching on these custom fields just as I would on a native field (which I assume will be much slower than operating on native fields.)  But the scale is to have a few dozen custom fields per Widget and each User will only have a few thousand Widgets in their inventory.  I can also probably batch most of the searching/filtering on the custom fields into a backend script (maybe.)

推荐答案

所有自定义属性与序列化的dict。我在最近的一个项目中使用了它,它的工作效果非常好。

Consider representing all custom properties with serialized dict. I used this in a recent project and it worked really well.

 class Widget(models.Model):
      owner = models.ForeignKey(auth.User)
      props = models.TextField(blank=True) # serialized custom data

      @property
      def props_dict(self):
          return simplejson.loads(self.props)

 class UserProfile(models.Model)
      user = models.ForeignKey(auth.User)
      widget_fields = models.TextField(blank=True) # serialized schema declaration

这篇关于如何在Django模型中存储任意的名称/值密钥对?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆