Search code examples
djangodjango-modelsforeign-keys

Django: ForeignKey choices with limit_choices_to not distinct in Admin


I have the following models in Django 1.3:

class A(models.Model):
    # fields

class RelatedToA(models.Model):
    a = models.ForeignKey(
        A, 
        related_name="related_set"
    )
    # fields

class B(models.Model):
    a = models.ForeignKey(
        A,
        limit_choices_to={'related_set__isnull'=False}
    )

Now in ModelAdmin for B, there are multiple entries of every instance of A in the dropdown. Is there a way to get the choices distinct on model level?


Solution

  • You could probably do that with formfield_for_foreignkey you could pass a custom query to be evaluated for the foreign key values in the drop down menu. See https://docs.djangoproject.com/en/dev/ref/contrib/admin/ for formfield_for_foreignkey.