如何获取limit_choices_to(Django)中的实体实例? [英] How to get instance of entity in limit_choices_to (Django)?
问题描述
例如:
class Foo(models.Model):
bar = models.OneToOneField(
'app.Bar',
limit_choices_to=Q(type=1) & Q(foo=None) | Q(foo=instance)
)
class Bar(models.Model):
TYPE_CHOICE = (
(0, 'hello'),
(1, 'world')
)
type = models.SmallIntegerField(
choices=TYPE_CHOICE,
default=0
)
$ b $我想在Django管理中只显示这些具有 type = 1
的这些条,与Foo没有关系,并显示已编辑实体的链接栏(如果是是的)
I wanna show in Django admin only these Bars that have type = 1
, that haven't relations with Foo's, and show linked Bar of edited entity (if it is).
当然,我们可以通过覆盖 admin的
,但是我们想通过 formfield_for_foreignkey
.ModelAdmin limit_choices_to
来实现。
Of course, we can do it via overriding formfield_for_foreignkey
method of admin.ModelAdmin
, but we want do this via limit_choices_to
.
如何获取实例的编辑实体?
How to get instance of edited entity?
推荐答案
如果您通过callable to limit_choices_to
引用当前实例。因此,您无法根据当前实例进行过滤。
If you pass a callable to limit_choices_to
, that callable has no reference to the current instance. As such, you can't filter based on the current instance either.
还有其他几种方法可以实现所需的功能,例如覆盖 formfield_for_foreignkey()
,或者在表单的 __ init __()
方法中覆盖表单域的查询集。 limit_choices_to
只不过是其中之一。
There are several other ways to achieve what you want, such as overriding formfield_for_foreignkey()
as you mentioned, or overriding the formfield's queryset in the form's __init__()
method. limit_choices_to
just isn't one of them.
这篇关于如何获取limit_choices_to(Django)中的实体实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!