About | Blog | xapy

All articles, tagged with “legacy database”

Django ManyToMany field with custom column names

Some time ago i had a task, similar to that, described in django’s Integrating with a legacy database. Among other, i had a task to integrate django admin with existing database, and a small question appeared, which was not answered on the net that time. The question was: We have a table with many-to-many mapping in the database (model1 <-> model2). We want to describe this, using django usual relations. Of course, the best description is the standard ManyToManyField, but one issue appeared: by default it creates a table (with name, configurable with keyword-argument db_table) containing fields, called model1_id and model2_id respectively. As i had pre-defined db schema, its fields’ names, of course, didn’t fit this naming convention, so it required some other solution. So the task is: there is
Product model with guid field and Category model with id field. By default we have a table with columns product_id, category_id and want: guid, manual_classification. And the simple solution is:

class ManyToManyFieldWithCustomColumns(models.ManyToManyField):
    def _get_m2m_column_name(self, related):
        return related.model._meta.pk.db_column
    def _get_m2m_reverse_name(self, related):
        return self.db_column

This can be used as:

categories = ManyToManyFieldWithCustomColumns(Category,db_column='manual_classification',              
                                              db_table='product_classification')

I’m sure there must be a better way of achieving this, for example improving other column’s name (i’ve taken pk’s name). If anybody have something to say — welcome to comments :)