How to get instance of entity in limit_choices_to (Django)?
<p>For instance:</p>

<pre><code>class Foo(models.Model):
    bar = models.OneToOneField(
        'app.Bar',
        limit_choices_to=Q(type=1) &amp; Q(foo=None) | Q(foo=instance)
    )


class Bar(models.Model):
    TYPE_CHOICE = (
        (0, 'hello'),
        (1, 'world')
    )
    type = models.SmallIntegerField(
        choices=TYPE_CHOICE,
        default=0
    )
</code></pre>

<p>I wanna show in Django admin only these Bars that have <code>type = 1</code>, that haven't relations with Foo's, and show linked Bar of edited entity (if it is).</p>

<p>Of course, we can do it via overriding <code>formfield_for_foreignkey</code> method of <code>admin.ModelAdmin</code>, but we want do this via <code>limit_choices_to</code>.</p>

<p>How to get instance of edited entity? </p>

<p>If you pass a callable to <code>limit_choices_to</code>, that callable has no reference to the current instance. As such, you can't filter based on the current instance either.</p>

<p>There are several other ways to achieve what you want, such as overriding <code>formfield_for_foreignkey()</code> as you mentioned, or overriding the formfield's queryset in the form's <code>__init__()</code> method. <code>limit_choices_to</code> just isn't one of them. </p>

python django