﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
29855	Admin form crashes when limit_choices_to query returns non-distinct results	Karolis Ryselis	nobody	"consider the following models:


{{{
class Warehouse(models.Model):
    branch = models.ManyToManyField(to=""Branch"")


class Branch(models.Model):
    title = models.CharField(max_length=32)


class Order(models.Model):
    warehouses = models.ForeignKey(to=""Warehouse"", limit_choices_to={""branch__title__startswith"": ""A""}, on_delete=models.PROTECT)

}}}

All models are registered using default `admin.ModelAdmin`.
Consider the following data entered:
Branch with name ""A branch""
Branch with name ""Another branch""
Warehouse related to both branches.

When trying to add a new order, the same warehouse is duplicated two times in the select box. When trying to save it, it crashes with error


{{{
get() returned more than one Warehouse -- it returned 2!
}}}

The function that crashes is `apply_limit_choices_to_to_formfield`. It performs a complex query with whatever we passed to `limit_choices_to` in field declaration and the result is not a distinct queryset. It is possible to work around this by creating a form for `Order`, overriding its `__init__` and adding `self.fields[""warehouse""].queryset = self.fields[""warehouse""].queryset.distinct()`. However, I think that this should at least not crash.
"	Bug	closed	Forms	2.1	Normal	duplicate			Unreviewed	0	0	0	0	0	0
