Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django multiple models, same table

I have a legacy database, with a table that represents nodes in the filesystem. There are few types of nodes e.g. A, B, C and different types have different properties. In current database design there is one table that holds the information about a node. If the node is of type A then only fields relevant to the type A are set. Now I would like to express the types A, B, C as models. The problem that arises is:

  1. I would like to have such behaviour, all the three types have a name property. I would like to filter all the nodes in the filesystem by name property and get a list of objects of good types.

  2. Each node as a parent link, expressed as foreign key in the database, so probably some form of inheritance should take place.

Is it possible in django?

like image 286
user1705926 Avatar asked Dec 11 '12 09:12

user1705926


1 Answers

Yes, it is possible. Here is an example:

models.py

from django.db import models

# Create your models here.
class NodeA(models.Model):

    name_a = models.CharField(max_length=75, blank=True, null=True)

    class Meta:
        db_table = 'Nodes'
        managed = False

class NodeB(models.Model):

    name_b = models.CharField(max_length=75, blank=True, null=True)

    class Meta:
        db_table = 'Nodes'
        managed = False

class NodeC(models.Model):

    name_c = models.CharField(max_length=75, blank=True, null=True)

    class Meta:
        db_table = 'Nodes'
        managed = False

Database schema (SQLITE)

 Nodes {
    id        integer   primary key
    name_a    TEXT
    name_b    TEXT
    name_c    TEXT }

Proof of concept

import NodeA, NodeB, NodeC

a = NodeA()
a.name_a = 'Node A'
a.save()

b = NodeB()
b.name_b = 'Node B'
b.save()

c = NodeC()
c.name_c = 'Node C'
c.save()

This produces:

id        name_a        name_b        name_c
1         Node A
2                       Node B
3                                     Node C
like image 135
D.A Avatar answered Oct 21 '22 10:10

D.A