开发者

Django: How to define a dynamic initial value on a ForeignKey Model Field

开发者 https://www.devze.com 2023-01-14 02:38 出处:网络
How can one define a dynamic initial value on a foreign key field? With the code: from django.db import models

How can one define a dynamic initial value on a foreign key field?

With the 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've the following error:

site = models.ForeignKey(Site, initial=setti开发者_运维知识库ngs.SITE_ID)
Field.__init__(self, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'initial'

I also tried with:

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

Thanks in advance


Model fields don't take an "initial" parameter, they take "default".


Override the save() method of the model and check if the field's value is None.


If I understand you right about the dynamic part, this is related to a Django foreign key FAQ, and James Bennett's Django tips: auto-populated fields (see The Holy Grail subhead :-).

0

精彩评论

暂无评论...
验证码 换一张
取 消