attaboyabhipro
attaboyabhipro

Reputation: 1648

Django : Create More Than One Tables with Same Model Schema

I have a Django model from which I need to derive many tables. Something like a factory. The schema of all tables is same but the table name is different. e.g.

class MyModel(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=100,blank=False)

    class Meta:
        db_table = 'mytable'

I need that in database, I have tables mytable01, mytable02, mytable03 ...

What is the best way to do this in models.py

Upvotes: 2

Views: 2196

Answers (1)

Matt Williamson
Matt Williamson

Reputation: 40193

You can sublcass a single abstract model.

# No table, since abstract = True
class BaseModel(models.Model):
    class Meta:
        abstract = True
    name = models.CharField(max_length=100,blank=False)

# Table name "myapp_submodel"
class SubModel(BaseModel):
    pass

# Table name "myapp_anothersubmodel"
class AnotherSubModel(BaseModel):
    nickname = models.CharField(max_length=100,blank=False)

More info at https://docs.djangoproject.com/en/dev/topics/db/models/#abstract-base-classes

Upvotes: 7

Related Questions