Ask Your Question
2

How can we specify the database in which a model (table) should be created in Django?

asked 2022-03-14 11:00:00 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-07-28 19:00:00 +0000

huitzilopochtli gravatar image

In Django, we can specify the database in which a model (table) should be created by defining the database in the settings.py file. We can have multiple databases defined in the settings.py file, each with a unique name and set of configurations.

To specify the database for a particular model, we can use the Meta class within the model and set the db_table attribute to the name of the table we want to create in the specified database.

For example, if we want to create a table called mytable in a database named mydatabase, we can define a model as follows:

class MyModel(models.Model):
    # fields definition

    class Meta:
        db_table = 'mytable'
        app_label = 'myapp'
        managed = True
        using = 'mydatabase'

In the above code, the db_table attribute specifies the name of the table to be created in the database, using attribute specifies the name of the database to use, and app_label attribute specifies the name of the app containing this model. The managed attribute is set to True, which means Django should create the table for this model when running migrations.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-03-14 11:00:00 +0000

Seen: 17 times

Last updated: Jul 28 '21