Django: how to define a dynamic seed value in a ForeignKey model field

How to define a dynamic initial value in a foreign key field?

With code:

from django.db import models
from django.conf import settings
from django.contrib.sites.models import Site

class Example(models.Model):
    site = models.ForeignKey(Site, initial=settings.SITE_ID)

I have the following error:

site = models.ForeignKey(Site, initial=settings.SITE_ID)
Field.__init__(self, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'initial'

I also tried:

class Example(models.Model):
    site = models.ForeignKey(Site, initial=Site.objects.get(id=settings.SITE_ID))

Thanks in advance

+3
source share
3 answers

The model fields do not accept the "initial" parameter, they accept the "default".

+4
source

Override the save()model method and check to see if the field value is specified None.

+1
source

, " Django" , Django: (. The Holy Grail :-).

0

Source: https://habr.com/ru/post/1762143/


All Articles