Description
I am using the SortedManyToManyField field from django-sortedm2m as in the following in my models:
from django.db import models
from sortedm2m.fields import SortedManyToManyField
class Category(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
parent = models.ForeignKey(
to="self", on_delete=models.SET_NULL, null=True, blank=True, related_name="subcategories",
)
name = models.CharField(max_length=250)
class Product(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=250)
categories = SortedManyToManyField(to=Category, blank=True, related_name="product_items")
Now, lets create and add some data to both the fields:
# create some categories
c1 = Category.object.create(name="C1")
c2 = Category.object.create(name="C2")
c3 = Category.object.create(name="C3")
# create some products
p1 = Product.object.create(name="P1")
p2 = Product.object.create(name="P2")
p3 = Product.object.create(name="P3")
# add categories to product P1
p1.categories.add(c1, c2, c3)
# add products to category C1
c1.product_items.add(p1, p2, p3)
Now, what happens is that the categories are inserted and retrieved in the correct order, where as products added to product_items are not.
When I checked the underlying class type of the field p1.categories, it says that its <class 'sortedm2m.fields.create_sorted_many_related_manager..SortedRelatedManager'> where as when I do the same for the reverse relation (product_items) it says <class 'django.db.models.fields.related_descriptors.create_forward_many_to_many_manager..ManyRelatedManager'>
Does this mean that the order is saved explicitly for the field that defines the SortedManyToManyField field and not the related_name/ reverse relation? Do I have to explicitly define the field product_items as a SortedManyToManyField field on the Category model?
I really have been trying to figure this out, but with no lack. I appreciate any help.