1

A Collection object can contain several Item objects, and an Item object can be contained by several Collection objects. The items should be ordered in each collection. I am using django-sortedm2m:

from sortedm2m.fields import SortedManyToManyField

class Item(models.Model):
    pass

class Collection(models.Model):
    items = SortedManyToManyField(to=Item)
>>> item_1 = Item.objects.create()
>>> item_2 = Item.objects.create()
>>> collection = Collection.objects.create()
>>> collection.items.set([item_2, item_1])
>>> collection.items.all()
<QuerySet [<Item 2>, <Item 1>]>

As expected, the order of items as they have been added is preserved. However, I want to reorder these elements, in the spirit of a "classic" model with ForeignKeyField and order_with_respect_to: collection.set_item_order([1, 2]). What is the best or simplest way to do that?

0 Answers0