How would you inherit from and override the django model classes to create a listOfStringsField?

后端 未结 5 2116
轻奢々
轻奢々 2021-02-06 05:24

I want to create a new type of field for django models that is basically a ListOfStrings. So in your model code you would have the following:

models.py:

5条回答
  •  北荒
    北荒 (楼主)
    2021-02-06 05:47

    I also think you're going about this the wrong way. Trying to make a Django field create an ancillary database table is almost certainly the wrong approach. It would be very difficult to do, and would likely confuse third party developers if you are trying to make your solution generally useful.

    If you're trying to store a denormalized blob of data in a single column, I'd take an approach similar to the one you linked to, serializing the Python data structure and storing it in a TextField. If you want tools other than Django to be able to operate on the data then you can serialize to JSON (or some other format that has wide language support):

    from django.db import models
    from django.utils import simplejson
    
    class JSONDataField(models.TextField):
        __metaclass__ = models.SubfieldBase
    
        def to_python(self, value):
            if value is None: 
                return None
            if not isinstance(value, basestring): 
                return value
            return simplejson.loads(value)
    
        def get_db_prep_save(self, value):
            if value is None: 
                return None
            return simplejson.dumps(value)
    

    If you just want a django Manager-like descriptor that lets you operate on a list of strings associated with a model then you can manually create a join table and use a descriptor to manage the relationship. It's not exactly what you need, but this code should get you started.

提交回复
热议问题