[Answered ]-Invalid literal for int() error in ForeignKey default

2👍

As noted in the comments, ForeginKeys are expected to be the primary keys (e.g. an integer), or an instance of the model.

However I believe you are running into a deeper issue with ForeignKey default values in Django.

Because that value needs to be available to Django when the model is loaded.

You’re not going to be able to make a Region query, get the object’s primary key and use that as the default foreign key, and that value will need to be available for the migration script too, which are incompatible with lambda functions that you may cook up to get the foreign key value.

More on the issues on this topic in this question.

If you really need a default value for that foreign key, I suggest you use a fixture with the Region object, remember it’s primary key, then hardcode that into the foreign key value

e.g. a fixture like this

model: app.Region
pk: 1
fields:
    name: 'North'

then use:

region = models.ForeignKey(Region, default=1)
👤bakkal

Leave a comment