Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using model inheritance and encounting by non-nullable field error

I used inheritance model in my project after changing the model; but I give non-nullable field error. What should I do? I am using Django 1.7

class Questions(models.Model):
    question_category = models.ForeignKey(Course, blank=False)
    question_author = models.ForeignKey(Author, blank=False)
    question_details = models.CharField(max_length=100, blank=False, default='')
    timestamp = models.DateTimeField(auto_now_add=True)

class TypeFive(Questions):
    question_title = models.CharField(max_length=100, blank=False, default=generator(5), unique=True, editable=False)

    def __str__(self):
        return "{}".format(self.question_title)


class TypeFiveChoice(models.Model):
    question_choice = models.ForeignKey(TypeFive)
    is_it_question = models.BooleanField(default=False)
    word = models.CharField(default='', blank=False, max_length=20)
    translate = models.CharField(default='', blank=False, max_length=20)
    timestamp = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return "{} : {}, {}".format(self.question_choice, self.word, self.translate)

After migrations:

You are trying to add a non-nullable field 'questions_ptr' to typefive without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows)
 2) Quit, and let me add a default in models.py
like image 653
altruistic Avatar asked Apr 20 '15 19:04

altruistic


1 Answers

In order to inherit from Questions in TypeFive, Django needs to add a relation from TypeFive to Questions. For all records in TypeFive that might already be in the database.

Django now doesn't know which question it should relate TopFive to. This is what the migrate command asks you for. You have a few options, but they greatly depend on your use case and whether you are in early development or if there is a production database where this migration has to run later.

I'm in early development and running it on localhost, so iI don't care about my records. Now, what should I do?

In this case you haven't much to worry about, when migrate asks you type 1 and then press enter. Now add a primary key of a Questions instance that is in your database and then hit enter again.

Django now relates all TypeFive instances that are currently in the database to this question, so you might have to clean that up afterwards (e.g. by editing the TypeFive in Django admin).

like image 132
sthzg Avatar answered Oct 24 '22 12:10

sthzg