uralbash / sqlalchemy_mptt

SQLAlchemy nested sets mixin (MPTT)
http://sqlalchemy-mptt.readthedocs.io
MIT License
196 stars 32 forks source link

null value in column \"lft\" violates not-null constraint #72

Open SanskarSans opened 3 years ago

SanskarSans commented 3 years ago

I am using this library for category table in my fastapi application. When I try to create a category, I get null value in column \"lft\" violates not-null constraint error. Here is the code setup

from sqlalchemy_mptt.mixins import BaseNestedSets

class Category(Base, BaseNestedSets, TimestampMixin):
    id = Column(Integer, primary_key=True, index=True)
    title = Column(String(255), nullable=False)
    slug = Column(String, index=True, unique=True)
    description = Column(Text())
    # parent_id = Column(Integer(), default=0)
    products = relationship("Product", back_populates="category")
    background_img = Column(String(255))

    def __init__(self, *args, **kwargs) -> None:
        generate_slug(self, sluggable_column="title", *args, **kwargs)
        super().__init__(*args, **kwargs)

    def __str__(self):
        return f"<Category {self.title}>"

class Product(Base, TimestampMixin):
    id = Column(Integer, primary_key=True, index=True)
    title = Column(String(255), nullable=False)
    slug = Column(String, index=True, unique=True)
    description = Column(Text())
    # to establish a bidirectional relationship(many to one) through relationship and back_ref
    category_id = Column(Integer, ForeignKey("category.id"))
    category = relationship("Category", back_populates="products")

async def resolve_create_category(db, data, parent_id):
    print("parent_id", data, parent_id)
    qs = Category.__table__.select().where(Category.__table__.c.title == data.title)
    category = await db.fetch_one(query=qs)
    print('category', category)
    if category:
        return CategoryCreatePayload(
            category=None,
            errors=[
                Error(
                    code="CATEGORY_ALREADY_EXIST",
                    message=f"Category with title {data.title} already exist",
                )
            ],
        )
    # check if parent id is sent
    if parent_id:
      query = Category.__table__.insert().values(
        title=data.title,
        description=data.description
    )
    # otherwise root value
    else:
      query = Category.__table__.insert().values(
          parent_id=parent_id,
          title=data.title,
          description=data.description
      )
    print("query", query)
    category_id = await db.execute(query)
    print("category_id", category_id)
    response_payload = {**data.__dict__, "id": category_id}
    print("response_payload", response_payload)
    return CategoryCreatePayload(category=Category(**response_payload))

print("parent_id", data, parent_id) gives

parent_id CategoryCreateInput(title="Men's", slug=None, description='Mens category') None

this is what printed by print('query', query) statement

query INSERT INTO category (created_at, updated_at, title, description, level, parent_id) VALUES (CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, :title, :description, :level, :parent_id)

It could not reach up to the line print("category_id", category_id)