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])
Should this work?
Yes, you can define a column with a default value of 0 as a Foreign Key. However, for the constraint to work, you would need to have a row in the source table with a value of 0 as well. Example: CREATE TABLE dbo.
Introduction to Django Foreign Key. A foreign key is a process through which the fields of one table can be used in another table flexibly. So, two different tables can be easily linked by means of the foreign key. This linking of the two tables can be easily achieved by means of foreign key processes.
A one-to-one relationship. Conceptually, this is similar to a ForeignKey with unique=True , but the "reverse" side of the relation will directly return a single object. In contrast to the OneToOneField "reverse" relation, a ForeignKey "reverse" relation returns a QuerySet .
According to documentation, An AutoField is an IntegerField that automatically increments according to available IDs. One usually won't need to use this directly because a primary key field will automatically be added to your model if you don't specify otherwise.
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)
Because get_or_create
returns a tuple, I think this is a better solution
def get_default():
result, _ = Foo.objects.get_or_create(id=1)
return result
than this
return Foo.objects.get_or_create(id=1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With