kAldown
kAldown

Reputation: 626

Django add non-nullable field (ForeignKey)

I need to add ForeignKey field to model, but makemigrations returns error to set default. But I won't any default value.

For example

@python_2_unicode_compatible
class Doctor(models.Model):
    name = models.CharField(max_length=250)
    surname = models.CharField(max_length=250)
    middlename = models.CharField(max_length=250)
    city = models.CharField(max_length=250)
    specialization = models.ForeignKey('Specialization', blank=True)

    def __str__(self):
        return "%s %s" % (self.name, self.surname)

@python_2_unicode_compatible
class Specialization(models.Model):
    name = models.CharField(max_length=250)
    #spec_table_name = models.ForeignKey('SpecializationTable')

    def __str__(self):
        return self.name

class Consultation(models.Model):
    client_id = models.ForeignKey('Client')
    doctor_id = models.ForeignKey('Doctor')

    #how to dropdown from doctor
    #record_id = models.ForeignKey(Specialization)

@python_2_unicode_compatible
class SpecializationTable(models.Model):
    name = models.CharField(max_length=250)

    def __str__(self):
        return self.name

class SpecializationTableRow(models.Model):
    row_name = models.CharField(max_length=250)
    row_description = models.CharField(max_length=999)
    row_required = models.BooleanField()
    table_name = models.ForeignKey(SpecializationTable)

That is the model I already have, when I try to uncomment ForeignKey in Specialization - error appers. If I delete all migrations, and start from scratch - there would be no error.

And moreover - I have no records at all (clean db).

How to pass this error, and don't drop\create db from scratch ?

Upvotes: 3

Views: 3854

Answers (1)

user2390182
user2390182

Reputation: 73470

The problem from django's point of view is that it has to know what to do with existing records of the Specialization model. It cannot know that there aren't any of those.

If you have a clean db, as you say, you can unapply the migrations to the point where the model in question is created. Let's assume Specialization is created in a migration called 0003_*, you can call:

> python manage.py migrate <app_name> 0002

Then you can delete all migration files in the app starting from 0003. Then, makemigrations will work again. If it it is created in 0001, you must do:

> python manage.py migrate <app_name> zero

This being said, the default value you provide during makemigrations is not preserved in any way (it will only be applied to existing records during migrate). So, if you have an empty database, providing any value (e.g. 1) will not have any effect at all.

Upvotes: 3

Related Questions