jazzband / django-taggit

Simple tagging for django
https://django-taggit.readthedocs.io
BSD 3-Clause "New" or "Revised" License
3.33k stars 622 forks source link

Tag Ordering Inconsistent #870

Closed steverecio closed 3 months ago

steverecio commented 12 months ago

Looking at the docs, it appears that the tags.all() queryset should maintain the ordering of the tags as they were initially set. However, in testing this does not hold. The tags do not in fact maintain their original ordering. How can I retrieve the tags with their original ordering intact?

Please note the sample below which shows that the ordering is not maintained as the docs show.

>>> apple = Food.objects.create()
>>> apple
<Food: Food object (1)>
>>> apple.tags.add("red", "green", "delicious")
>>> apple.tags.all()
<QuerySet [<Tag: green>, <Tag: red>, <Tag: delicious>]>
steverecio commented 11 months ago

The issue seems to stem from the use of unordered sets here: https://github.com/jazzband/django-taggit/blob/master/taggit/managers.py#L196

rtpg commented 11 months ago

Looking at the docs, it appears that the tags.all() queryset should maintain the ordering of the tags as they were initially set.

did you see that anywhere? Or is this just what you saw in the docs

Basically my feeling here is that Manager has an ordering property in the description. If you care about the insertion order, you can set this to pk. If you don't then we let the DB do what it wants.

Having said that... the change you sent in the PR makes it seem like we're dealing with a slightly different issue (where when we are creating them, the cached model instance list doesn't match the passed in values). I don't know what to think of that.

If anything I feel like the default ordering of name would make more sense? Though that ordering is less obvious in non-latin languages.


Anyways, questions I'm mulling over:

steverecio commented 11 months ago

did you see that anywhere? Or is this just what you saw in the docs

The readme indicates this is the default behavior. This intuitively makes the most sense to me. If I add tags in a particular order, I would expect them to be returned in that same order. For example, on our site we have a form where you can add a set of tags and save. However, after saving, the order of tags is unpredictable.

The problem is the manager reorders the tag list by adding them to a set which removes the agency of the developer to impose their own desired ordering. If you wanted to impose any particular order (tag creation date, tag name, etc) then that sorting can be handled prior to calling mymodel.tags.set(...my_tag_list). Similarly, if I iterated over a list and called mymodel.tags.add(tag) for each tag, I would expect that order to be respected when I retrieve the results.

I think the possible tag orderings are the following:

rtpg commented 3 months ago

Fixed in #892