获取 Django 管理内联中使用的 form_class 中的外键实例
我有一个使用自定义表单类的内联管理。如何从该表单类的函数中访问父实例(外键)?
相关代码如下:
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。
I have an admin inline that uses a custom form class. How can I access the parent instance (foreign key) from within the functions of that form class?
Relevant code below:
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
I know that once there is an actual instance, I can access it using instance.bar
. However, that only works once there's acually a record, right? So if I am using this form to create a record, instance is going to be None.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试一下:
希望对您有帮助。
Give this a try:
Hope that helps you out.