sc28
sc28

Reputation: 1213

Django model for a legacy table containing a custom data type

I am working with a Postgresql legacy table and found that some fields have custom data types.

For example, instead of e.g. character varying, the column color has color_type as data type, with permissible options [red|green|blue|black].

Relying on the inspectdb command, the automatically generated model contains the following line and comment:

color = models.TextField(blank=True, null=True)  # This field type is a guess.

I would "clean" this line as described in the following class, but am not sure a) if it will properly "fit" the existing table (e.g. if I write new objects inside the table), and b) whether if migrated to a new database, the custom_type would be correctly reproduced:

class Things(models.Model):
    name = models.CharField(max_length=30, null=True, blank=True) 

    RED = 'red'
    GREEN = 'green'
    BLUE = 'blue'
    BLACK= 'black'
    COLOR_CHOICES = (
                      (RED, 'red'),
                      (GREEN, 'green'),
                      (BLUE, 'blue'),
                      (BLACK, 'black'),
                     )
    color = models.CharField(       
                               max_length = 10, 
                               choices = COLOR_CHOICES,
                               default = RED, 
                               null = True, 
                               blank = True
                            )

    def __str__(self):
        return self.name

    class Meta:
        managed = False
        db_table = 'myuser'

What is the proper way to reflect this custom data type in the Django model?

Upvotes: 0

Views: 209

Answers (1)

Bernhard Vallant
Bernhard Vallant

Reputation: 50796

You can write a Custom Field which uses a custom defined database type:

class ColorField(models.Field):
    def db_type(self, connection):
        return 'enum("red","green","blue","black")'

Upvotes: 1

Related Questions