Saurabh Verma
Saurabh Verma

Reputation: 6728

Common app_label for all the models in Django

I have many classes in models.py something like:

class SomeClass1(BaseModel):
    question = models.ForeignKey(Question)
    image = models.ForeignKey(Image)

class SomeClass2(BaseModel):
    question = models.ForeignKey(Question)
    option_text = models.TextField()

Now, I want to add app_label = 'my_app_label1' to all of these classes, something like this:

class SomeClass1(BaseModel):
    question = models.ForeignKey(Question)
    image = models.ForeignKey(Image)
    class Meta:
        app_label = 'my_app_label1'

But since there are many classes, so instead of adding app_label = 'my_app_label1' to all the classes, I'm adding app_label = 'my_app_label1' to the BaseModel, like this:

class BaseModel(models.Model):
    """
    For future abstraction.
    """
    class Meta:
        app_label = 'ques_app_data'

After which I'm getting this error:

myapp.SomeClass1.basemodel_ptr: (fields.E300) Field defines a relation with model 'BaseModel', which is either not installed, or is abstract.

Can anyone please explain how to solve this ?

Upvotes: 2

Views: 15066

Answers (2)

Saurabh Verma
Saurabh Verma

Reputation: 6728

This post answers this question: makemigrations not detecting changes for Extended Models in Django 1.7

having 2 major points:

1) We must have

class Meta:
        abstract = True

in BaseClass

2) app_label ques_app_data is must be included in INSTALLED_APPS

Upvotes: 1

Rahul Gupta
Rahul Gupta

Reputation: 47876

Try specifying abstract=True in BaseModel inner Meta class.

class BaseModel(models.Model):
    """
    For future abstraction.
    """
    class Meta:
        abstract=True # specify this model as an Abstract Model
        app_label = 'ques_app_data'

Then inherit this BaseModel class in your model classes.

All the child model classes inherit the Meta class attributes of parent BaseModel class. Django will make one adjustment though to the Meta class of an abstract base class, before installing the Meta attribute in a child class, it sets abstract=False. This is done so that children of abstract base classes don’t automatically become abstract classes themselves.

After doing this, you will need to run the migrations again.

Note: There must be an app in your project by the name ques_app_data for this to work.

Upvotes: 3

Related Questions