作为达到我的目标的另一种方式,在那里描述:Get django default model field value to be a parent attribute value,即:将动态默认字段值设置为我的内联“localwanted”子字段,它等于其父项相当于 “remotewanted”获取django ChildInline父模型字段值时添加新的额外
我有以下两种模式:
#models.py
class Parent(models.Model):
id = UUIDField(primary_key=True)
remotewanted = models.CharField(max_length=100)
class Child(models.Model):
parent = models.ForeignKey(Parent)
localwanted = models.CharField(max_length=100)
def parent_remotewanted(self):
return self.parent.remotewanted
如果我想localwanted为 “AAA” 默认:
#admin.py
class ChildForm(forms.ModelForm):
class Meta:
model = Child
exclude = []
def __init__(self, *args, **kwargs):
super(ChildForm, self).__init__(*args, **kwargs)
self.initial['localwanted'] = "AAA"
class ChildInline(admin.TabularInline):
model = Child
extra = 1
form = ChildForm
class ParentAdmin(admin.ModelAdmin):
exclude = []
inlines = [ChildInline]
#list_display, etc
admin.site.register(Parent,ParentAdmin)
和它的作品,有额外的字段(这里只有一个)显示:“AAA”
但
如果想要这个默认值是动态的(即是父变量),并更换“AAA”通过self.instance.parent_remotewanted,如下所示(在ChildForm类中):
...
self.initial['localwanted'] = self.instance.parent_remotewanted.__self__
...
它不显示任何内容。
然后
试图直接与Parent.objects打交道,我的第二次尝试其他条件不变:
#models.py
class Child(models.Model):
parent = models.ForeignKey(Parent)
localwanted = models.CharField(max_length=100)
def parent_identity(self): #<----------------
return self.parent_id #<----------------
#admin.py
class ChildForm(forms.ModelForm):
class Meta:
model = Child
exclude = []
def __init__(self, *args, **kwargs):
super(ChildForm, self).__init__(*args, **kwargs)
self.initial['localwanted'] = self.instance.parent_identity #<----------------
我内嵌字段正确显示父ID字段。作为一个新手,这对我来说很神奇,因为“self.instance.parent_identity”最初不是一个字符串对象。
>>print self.instance.parent_identity
<bound method Child.parent_identity of <Child: >> #<--what print function gives
反正我信了,我可以用它玩,但不可能达到它的字符串表示,以这样做:
obj = Parent.objects.get(id=self.instance.parent_identity)
# or
obj = Parent.objects.get(id=self.instance.parent_identity.__self__)
两台显示器“匹配查询不存在”用DEBUG = TEMPLATE_DEBUG = True。 我开始意识到ChildForm init函数的确切功能。而且它似乎要处理的结构要比有效的对象更重要。
问题
这里有什么要做的吗? 我的方法是死路一条吗?
谢谢。是的,它是一个函数,但现在不必调用它,因为父类没有在此处实例化。我改变了我的观点,并做了不同的诀窍,如下所述:http://stackoverflow.com/questions/27409900/python-how-to-call-dictionnary-contained-callables-at-a-given-time?noredirect= 1#comment43264950_27409900 仅当类对象被实例化时调用可调用对象,@属性装饰器才是我的解决方案。 – Kanak