#How to create default Database Objects for models.ForeignKey(on_delete=models.SET_DEFAULT)

1 messages · Page 1 of 1 (latest)

heady ermine
#

Hello, I am new to django so this might be a very basic question, but I found the models.SET_DEFAULT Value for the on_delete Parameter for ForeignKeys. Unfortunatly I don't understand how to use it properly.

I thought it allowed me to create an object (and save it to the database) and then set this object as the default Parameter.
models.py:

from django.db import models

class Bar(models.Model):
    pass


class Foo(models.Model):
    
    bar = Bar()
    bar.save()

    bar = models.ForeignKey(Bar, on_delete=models.SET_DEFAULT, default=bar)

but it throws the following error:

ValueError: Cannot serialize: <Bar: Bar object (3)>
There are some values Django cannot serialize into migration files

I didn't find any resources reguarding that topic online, but the github projects I found all used the id of the ForeignKey Object like so:

from django.db import models

class Bar(models.Model):
    pass


class Foo(models.Model):
    
    bar_id = models.ForeignKey(Bar, on_delete=models.SET_DEFAULT, default=1, null=True)

my question is: is this the only way possible to set a default value for a ForeignKey? And my second question: Is there a way so the migrations create that first default object automaticly when you first populate the dataabes?

hot summit
#

I would tend to advise not to use a default value with ForeignKey. If you must, create a function that will look up the default value and use that instead. The id value can change and isn't guaranteed to exist.

Regarding loading data initially, you should look into data migrations and fixtures.
https://docs.djangoproject.com/en/4.1/howto/initial-data/
https://docs.djangoproject.com/en/4.1/topics/migrations/#data-migrations
https://docs.djangoproject.com/en/4.1/howto/initial-data/#providing-data-with-fixtures