Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you specify a default for the Django ForeignKey field?

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?

like image 855
Paul D. Waite Avatar asked Aug 16 '11 15:08

Paul D. Waite


People also ask

Can a ForeignKey have a default value?

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.

What is ForeignKey Django models?

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.

What's the difference between Django OneToOneField and ForeignKey?

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 .

What is AutoField in Django?

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.


2 Answers

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)
like image 199
radious Avatar answered Nov 08 '22 23:11

radious


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)
like image 43
bopajdowski Avatar answered Nov 09 '22 01:11

bopajdowski