Reputation: 1345
I am learning django by doing some tutorials and am currently on ownership in the effective-django tutorial. Unfortunately, the tutorials is written for an older version of django so some things are slightly different.
I am running into problems when adding an 'owner' field to my model Contact in models.py:
from django.db import models
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
class Contact(models.Model):
"""
Interface for contact class
"""
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
email = models.EmailField()
owner = models.ForeignKey(User)
def __str__(self):
return ' '.join([self.first_name, self.last_name])
def get_absolute_url(self):
return reverse('contacts-view', kwargs={'pk': self.id})
When trying to run 'makemigrations', i get warnings:
You are trying to add a non-nullable field 'owner' to contact without a default: can't do that
This makes sense for an existing database, so i tried flushing the database. However, the problem remains. What should be the default value for the field owner? I also tried making the field nullable but that gives me the error that field owner cannot be null.
Upvotes: 0
Views: 1359
Reputation: 19922
Well, it does not matter if the database is empty or not. It matters that you probably have already at least one migration that first creates the model, and then you try to run makemigrations
that adds the field.
If these migrations are not too important for you (which I recon they are not since this is a tutorial), just delete all previous migrations and run makemigrations
fresh.
Alternatively, you would have to manually change migrations, possibly provide a default value etc.
Upvotes: 1
Reputation: 45595
I usually set to 1
. In this case already existed records will be assigned to the first user.
If you want you can later reassign these records in the next data migration.
Upvotes: 2