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 :-).
精彩评论