问题
I've had a read through http://www.b-list.org/weblog/2006/jun/06/django-tips-extending-user-model/ but still am having problems migrating my new db schema with a ForeignKey for a user in a list of products
a simplified version of my code is:
from django.contrib.auth.models import User
# other imports
class Product(models.Model):
author = models.ForeignKey(User)
# other product fields..
but when I try to migrate to South, and this may be the problem, as my user database is not handled by South (??forgive my newbieness) i'm getting errors that a default value needs to be set:
_mysql_exceptions.OperationalError: (1067, "Invalid default value for 'author_id'")
Can anyone explain what i'm doing wrong?? Ideally I wouldn't want a default value for the user, or at least null, false or 0 (but that doesn't seem to work)..
many thanks,
adam
回答1:
If you want it to be possible to have an empty value for author
, you need to define the ForeignKey with null=True
. You'll probably want blank=True
as well, as that controls the validation in Django forms.
author = models.ForeignKey(User, null=True, blank=True)
回答2:
Ended up taking the easy route and totally resetting the product table, and migrating from scratch which worked. Not sure i've learnt anything (other than how to reset an app)!
来源:https://stackoverflow.com/questions/4782438/django-default-foreign-key-value-for-users