Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change table name in Django

Tags:

python

django

I have read that the table name in Django can be customized using Meta Options. I'm wondering how the db_table option could be used to keep using the app name but modify the model name slightly without hardcoding the app name.

For example, from the Django tutorial, the app name is "polls" and the model name is "poll". Lets say I want the table to be called "polls_mypoll" instead of "polls_poll". Here is what I tried, but the outer class cannot be accessed (Poll is not defined)

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    class Meta:
        db_table = "%s_%s" % (Poll._meta.app_label, "mypoll")

Similarly, what if I wanted to define db_table explicitly to just be the default polls_poll? I know I could just leave off the class Meta entirely and that default name would be used, but what if I wanted to be explicit about it?

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    class Meta:
        db_table = "%s_%s" % (Poll._meta.app_label, Poll._meta.model_name)

This doesn't work, again because Poll is not defined inside Meta.

like image 357
fractalous Avatar asked Nov 24 '13 20:11

fractalous


1 Answers

The exception you are getting, Poll is not defined, is caused by your db_table = "%s_%s" % (Poll._meta.app_label, Poll._meta.model_name) statement referencing the Poll class while it is still being constructed (not yet inserted into the global scope). If you want to use references to Poll in the db_table, consider writing your own metaclass that inherits from ModelBase, and sets the _meta.db_table value properly. At that point, the Poll name won't be available, but the actual object will be constructed and at your hand to manipulate.

like image 189
Maciej Gol Avatar answered Oct 05 '22 15:10

Maciej Gol