tortoise-orm icon indicating copy to clipboard operation
tortoise-orm copied to clipboard

feat(model): added a class method to get table name of the model

Open ducminhgd opened this issue 2 years ago • 1 comments

Description

Added a class method name get_table_name for Model to get the name of the table that the Model represents

Motivation and Context

tortoise.expressions.F inherits pypika.Field

class Field(Criterion, JSON):
    def __init__(
        self, name: str, alias: Optional[str] = None, table: Optional[Union[str, "Selectable"]] = None
    ) -> None:
        super().__init__(alias=alias)
        self.name = name
        self.table = table

    def nodes_(self) -> Iterator[NodeT]:
        yield self
        if self.table is not None:
            yield from self.table.nodes_()

    @builder
    def replace_table(self, current_table: Optional["Table"], new_table: Optional["Table"]) -> "Field":
        """
        Replaces all occurrences of the specified table with the new table. Useful when reusing fields across queries.

        :param current_table:
            The table to be replaced.
        :param new_table:
            The table to replace with.
        :return:
            A copy of the field with the tables replaced.
        """
        self.table = new_table if self.table == current_table else self.table

    def get_sql(self, **kwargs: Any) -> str:
        with_alias = kwargs.pop("with_alias", False)
        with_namespace = kwargs.pop("with_namespace", False)
        quote_char = kwargs.pop("quote_char", None)

        field_sql = format_quotes(self.name, quote_char)

        # Need to add namespace if the table has an alias
        if self.table and (with_namespace or self.table.alias):
            table_name = self.table.get_table_name()
            field_sql = "{namespace}.{name}".format(
                namespace=format_quotes(table_name, quote_char),
                name=field_sql,
            )

        field_alias = getattr(self, "alias", None)
        if with_alias:
            return format_alias_sql(field_sql, field_alias, quote_char=quote_char, **kwargs)
        return field_sql

In the method get_sql, there is a line self.table.get_table_name().

So, when we use tortoise.expression.F(name='column_name', table=TableModelClass), there is an exception that get_table_name() method does not exist in TableModelClass.

==> So this pull request implements a class method to solve this problem.

Checklist:

  • [x] My code follows the code style of this project.
  • [x] I have read the CONTRIBUTING document.

ducminhgd avatar Nov 17 '23 02:11 ducminhgd

Hi @long2ice, I think it is just a simple PR, please help me to review it.

ducminhgd avatar Nov 21 '23 03:11 ducminhgd