django default foreign key value for users

为君一笑 提交于 2019-12-07 08:25:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!