Opened 6 years ago

Closed 6 years ago

#29855 closed Bug (duplicate)

Admin form crashes when limit_choices_to query returns non-distinct results

Reported by: Karolis Ryselis Owned by: nobody
Component: Forms Version: 2.1
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

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.

Change History (2)

comment:1 by Tim Graham, 6 years ago

Type: UncategorizedBug

Duplicate of #1891.

comment:2 by Tim Graham, 6 years ago

Resolution: duplicate
Status: newclosed
Note: See TracTickets for help on using tickets.
Back to Top