Django Proxy Field

Is it possible to create a Django Proxy field that has access to another field but does not store anything in the database for its own values ​​and does not have a database column for it?

In this case, we want to store the values ​​in JsonField, but be able to use the built-in Django field checks. A second advantage of this would be the ability to add new fields (with the ability to check) without affecting the database schema.

The sudo code will probably look something like this:

from django.db import models
from django.contrib.postgres.fields import JsonField

class ProxyInitMixin(object):

    def __init__(self, *args, *kwargs):
        # some logic that will hold values if set on the Model
        # but won't create a column or save anything to the
        # database for this Field.
        super(ProxyInitMixin, self).__init__(*args, **kwargs)

class ProxyIntegerField(ProxyInitMixin, models.Field):
    pass

class ProxyCharField(ProxyInitMixin, models.Field):
    pass

class MyModel(models.Model):
    proxy_int = ProxyIntegerField()
    proxy_char = ProxyCharField()
    data = JsonField()

    def save(self, *args, **kwargs):
        self.data = {
            'foo': self.proxy_int,
            'bar': self.proxy_char
        }
        return super(MyModel, self).save(*args, **kwargs)
+4
source share

All Articles