'ForeignKey error in ormar has no attribute 'get_column_alias'

I'm testing out ormar to avoid having to create models for both api and database and ran into an issue with foreignkey assignment I can't seem to figure out.

The base code works before I deleted the database and try to recreate again with the new foreignkey.

import databases
import ormar
import sqlalchemy
from datetime import datetime
from typing import Optional

database = databases.Database("sqlite:///db.sqlite")
# database = "postgresql://user:password@postgresserver/db"
metadata = sqlalchemy.MetaData()


class BaseMeta(ormar.ModelMeta):
    database = database
    metadata = metadata


class TaskTypes(ormar.ModelMeta):
    class Meta(BaseMeta):
        tablename = "tasktypes"

    id: int = ormar.Integer(primary_key=True)
    name: str = ormar.String(max_length=64)


class Tasks(ormar.ModelMeta):
    class Meta(BaseMeta):
        tablename = "tasks"

    id: int = ormar.Integer(primary_key=True)
    title: str = ormar.String(max_length=64)
    tasktypes: Optional[TaskTypes] = ormar.ForeignKey(TaskTypes)

the error is

File "/Repositories/MVP/backend/.venv/lib/python3.9/site-packages/ormar/fields/foreign_key.py", line 114, in populate_fk_params_based_on_to_model

fk_string = to.Meta.tablename + "." + to.get_column_alias(to.Meta.pkname)

AttributeError: type object 'TaskTypes' has no attribute 'get_column_alias'

Any help would be great. Thanks



Solution 1:[1]

Your models must inherit from ormar.Model and not ModelMeta.

So the valid code is:

import databases
import ormar
import sqlalchemy
from datetime import datetime
from typing import Optional

database = databases.Database("sqlite:///db.sqlite")
# database = "postgresql://user:password@postgresserver/db"
metadata = sqlalchemy.MetaData()


class BaseMeta(ormar.ModelMeta):
    database = database
    metadata = metadata


class TaskTypes(ormar.Model): # change here
    class Meta(BaseMeta):
        tablename = "tasktypes"

    id: int = ormar.Integer(primary_key=True)
    name: str = ormar.String(max_length=64)


class Tasks(ormar.Model): # change here
    class Meta(BaseMeta):
        tablename = "tasks"

    id: int = ormar.Integer(primary_key=True)
    title: str = ormar.String(max_length=64)
    tasktypes: Optional[TaskTypes] = ormar.ForeignKey(TaskTypes)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 collerek