#29855: Admin form crashes when limit_choices_to query returns non-distinct 
results
-------------------------------------------+------------------------
               Reporter:  Karolis Ryselis  |          Owner:  nobody
                   Type:  Uncategorized    |         Status:  new
              Component:  Forms            |        Version:  2.1
               Severity:  Normal           |       Keywords:
           Triage Stage:  Unreviewed       |      Has patch:  0
    Needs documentation:  0                |    Needs tests:  0
Patch needs improvement:  0                |  Easy pickings:  0
                  UI/UX:  0                |
-------------------------------------------+------------------------
 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.

-- 
Ticket URL: <https://code.djangoproject.com/ticket/29855>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-updates+unsubscr...@googlegroups.com.
To post to this group, send email to django-updates@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/050.c3aa83f95c3b494f5f2040e7de11ce34%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to