Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
516 views
in Technique[技术] by (71.8m points)

python - How to get instance of entity in limit_choices_to (Django)?

For instance:

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
    )

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).

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...