0

Django-mptt model does not order by (order_insertion_by) profile (ForeignKey), but it does after rebuild()

models.py

class Product(MPTTModel):
    # fields
    profile = models.ForeignKey(
        Profile,
        blank=True,
        null=True,
        on_delete=models.CASCADE,
    )
    # more fields
    class MPTTMeta:
        order_insertion_by = ['profile']

Profile is also an MPTT model connected to User by OneToOneField

models.py

class Profile(MPTTModel):
    # fields
    user = models.OneToOneField(User, on_delete=models.PROTECT)
    # more fields

    class Meta:
        abstrat = False
        ordering = ["user__last_name", "user__first_name", "user__username"]

    class MPTTMeta:
        parent_attr = "manager"

    def get_name(self):
        return f"{self.user.last_name}, {self.user.first_name}"
   
    def __str__(self):
        return self.get_name()

If I save some data, then order_insertion_by will order the data by id and not by last_name,first_name. But if I save and rebuild() the Product objects Product.objects.rebuild(), then it orders by last_name,first_name.

The structure is:

  • Product (root)
    • Product (child) (needs to be sorted by profile and is the only child which contains profile)
      • Product (child of child)
        • Product (child of child of child)

I want to understand why I need to use rebuild(), as rebuild() takes a lot of resources.

comp_boon
  • 79
  • 7

0 Answers0