[ACCEPTED]-How to store arbitrary name/value key pairs in a Django model?-django-models

Accepted answer
Score: 25

Consider representing all custom properties 2 with serialized dict. I used this in a 1 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
Score: 10

It looks like you've reinvented the triple 10 store. I think it's a common thing, as we 9 follow the idea of database flexibility 8 to its natural conclusion. Triple stores 7 tend to be fairly inefficient in relational 6 database systems, but there are systems 5 designed specifically for them.

http://en.wikipedia.org/wiki/Triplestore

At the scales 4 you're talking about, your performance is 3 likely to be acceptable, but they don't 2 generally scale well without a specialized 1 DB.

Score: 3

In my opinion, the best way to achieve this 7 sort of completely extensible model is really 6 with EAV (Entity, Attribute, Value). Its 5 basically a way to bring a schemaless non-relational 4 database to SQL. You can read a bunch more 3 about it on wikipedia, http://en.wikipedia.org/wiki/Entity-attribute-value_model but one of the better 2 implementation of it in django is from the 1 EveryBlock codebase. Hope it's a help!

http://github.com/brosner/everyblock_code/blob/master/ebpub/ebpub/db/models.py

Score: 0

http://github.com/tuttle/django-expando may be of interest to you.

0

Score: 0

When I had an object that could be completely 6 customized by users, I created a field on 5 the model that would contain some JSON in 4 the column. Then you can just serialize 3 back and forth when you need to use it or 2 save it.

However, it does make it harder 1 to use the data in SQL queries.

More Related questions