我有一个使用自定义表单类的管理内联。如何从该表单类的函数中访问父实例(外键)?
以下相关代码:
models.py:
class Bar(models.Model):
name = models.CharField(max_length=50)
class Foo(models.Model):
name = models.CharField(max_length=50)
bar = models.ForeignKey(Bar, null=True, blank=True, related_name="foos")
admin.py:
class FooInlineAdmin(admin.TabularInline):
model = Foo
form = AdminFooForm
max_num = 3
class Bar(admin.ModelAdmin):
inlines = [FooInlineAdmin]
forms.py:
class AdminFooForm(forms.ModelForm):
class Meta:
model = Foo
def clean(self):
data = self.cleaned_data
mybar = self.get_foreign_key_somehow() # this is the line I'm interested in
我知道一旦有实际的实例,我就可以使用instance.bar
访问它。但是,只有在有记录的情况下才有效,对吗?因此,如果我使用此表单创建记录,则实例将为None。
答案 0 :(得分:1)
尝试一下:
class FooInlineFormset(forms.models.BaseInlineFormSet):
def clean(self):
for form in self.forms:
try:
if form.cleaned_data:
delete = form.cleaned_data.get('DELETE')
if not delete:
bar = form.cleaned_data.get('bar', None)
except AttributeError:
pass
class FooInlineAdmin(admin.TabularInline):
model = Foo
formset = FooInlineFormset
form = AdminFooForm
max_num = 3
希望能帮到你。