jrief / django-admin-sortable2

Generic drag-and-drop ordering for objects in the Django admin interface
https://django-admin-sortable2.readthedocs.io/en/latest/
Other
770 stars 180 forks source link

Problem with admin Filters #266

Closed Sebastianopazo closed 2 years ago

Sebastianopazo commented 3 years ago

Hello! I am confused about a specific behavior.

Imagine I have a model 'Book' defined as follows.

class Book(models.Model):
    title = models.CharField(max_length=128)
    genre = models.ForeignKey('Genre', on_delete=models.PROTECT, null=True,  blank=True)
    position = models.PositiveIntegerField(default=0, blank=False, null=False)

   class Meta:
          ordering = ('position', )

and my admin settings look like this:

class BookAdmin(SortableAdminMixin, admin.ModelAdmin):
    list_display = ('title',)
    list_filter = ('genre',)

Here's the problem: whenever I filter by a specific genre, if I try to drag/drop to invert the order of two items, instead of exchanging the original positions, the sorting mechanism only uses as reference the first item (the one with the lowest position index).

For example:

Let's say I filter my list by a hypothetical genre 'Fantasy'. That leaves me with a list of books that don't necessarily have consecutive positions. Then, if I try swapping Book position 14 with Book position 55, the system will write positions 14 and 15 for those books. As a consequence, the system will generate more than one book with position 15 (the list already had a book position 15).

In the long run, this can cause a lot of trouble with the integrity of the list.

Am I simply not supposed to use filters?

jrief commented 3 years ago

I would consider this a bug in that sense, that ordering shall be deactivated if filters are active. Rethinking your problem, it's hard to resort in such a situation, because I have to swap values of position instead of reassigning them. If you can come up with a solution for this problem which works, this could be an interesting pull request.

Sebastianopazo commented 3 years ago

Thank you so much for the quick answer!

I will examine it and see if I can come up with something :)

jrief commented 2 years ago

closing for inactivity