Skip to content

Inherit Meta.ordering from abstract base models (#2046)#2236

Open
uttam12331 wants to merge 1 commit into
tortoise:developfrom
uttam12331:fix/inherit-abstract-meta-ordering-2046
Open

Inherit Meta.ordering from abstract base models (#2046)#2236
uttam12331 wants to merge 1 commit into
tortoise:developfrom
uttam12331:fix/inherit-abstract-meta-ordering-2046

Conversation

@uttam12331

Copy link
Copy Markdown

Summary

Closes #2046.

When a model defines its own Meta (for example to set table) but does not set ordering, the ordering declared on an abstract base model's Meta was silently dropped, so queries on the subclass came back unordered:

class BaseModel(Model):
    created_at = fields.DatetimeField(auto_now_add=True)
    class Meta:
        ordering = ["-created_at"]
        abstract = True

class Book(BaseModel):
    name = fields.CharField(max_length=255)
    class Meta:
        table = "books"

await Book.all()   # not ordered by -created_at

Root cause

ModelMeta.__new__ builds the model's MetaInfo from attrs.get("Meta", ...) — i.e. only the class's own Meta. When the subclass supplies its own Meta without ordering, the abstract base's ordering is never consulted.

Fix

After building the meta, if the subclass's own Meta does not define ordering, inherit the default ordering from the first base model that has one. This mirrors how abstract-base Meta options behave in similar ORMs.

Behavior is preserved for models that:

  • define their own ordering (theirs wins), or
  • define an explicitly empty ordering = [] (stays empty).

Tests

Added test_abstract_meta_ordering_is_inherited, covering inheritance, own-ordering-wins, and explicit-empty-stays-empty. It fails on develop and passes with this change. Existing test_inheritance.py / test_order_by.py still pass; ruff check/ruff format are clean; added a CHANGELOG entry.

When a model defined its own ``Meta`` (e.g. to set ``table``) but did not set
``ordering``, the ordering declared on an abstract base model's ``Meta`` was
lost, because ``ModelMeta.__new__`` reads ``Meta`` only from the class's own
attributes. As a result queries on the subclass came back unordered.

If the subclass's own ``Meta`` does not define ``ordering``, inherit the
default ordering from the first base model that has one. A subclass that
defines its own ``ordering`` (including an explicitly empty one) is
unaffected.

Closes tortoise#2046
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

subclass does not inherit parent's ordering

1 participant