如何为Django ForeignKey字段指定默认值? [英] How do you specify a default for the Django ForeignKey field?

查看:511
本文介绍了如何为Django ForeignKey字段指定默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用South将 ForeignKey 字段添加到Django模型中。我收到以下错误:

I’m trying to add a ForeignKey field to a Django model using South. I’m getting the following error:

ValueError: You cannot add a null=False column without a default value.

事实上,我确实为该字段指定了默认值,但是我不确定

I did, in fact, specify a default value for the field, but I’m not sure I did it correctly.

language = models.ForeignKey(Language, default=Language.objects.all()[0])

这可以吗?

推荐答案

AFAIK Django不会执行以参数形式传递的QuerySet,即使它仅限于一个元素。您应该在这篇文章中尝试类似建议的>

AFAIK Django won't execute a QuerySet passed as a param, even if it's limited to one element. You should try something like proposed in this post

class Foo(models.Model):
    a = models.CharField(max_length=10)

def get_foo():
    return Foo.objects.get_or_create(id=1)

class Bar(models.Model):
    b = models.CharField(max_length=10)
    a = models.ForeignKey(Foo, default=get_foo)

这篇关于如何为Django ForeignKey字段指定默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆