How to store arbitrary name/value key pairs in a Django model?

后端 未结 5 527
没有蜡笔的小新
没有蜡笔的小新 2021-02-03 11:02

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()
            


        
5条回答
  •  清歌不尽
    2021-02-03 11:29

    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
    

提交回复
热议问题