Home > Blockchain >  Error - Type Error DeclartativeMeta object got multiple values for keyword argument 'owner_id&#
Error - Type Error DeclartativeMeta object got multiple values for keyword argument 'owner_id&#

Time:12-23

i have a question, ive been banging my head against my desk for too long so iam taking it to stackoverflow. hope you guys can help me! :)

although i know the Error is very specific, i cant seem to get my head arround it. Iam trying to create a relationship that goes as follows A User has One Account and One Account has many trades. Still iam getting the error back:

TypeError: DeclarativeMeta object got multiple values for keyword argument 'owner_id'

if someone could please explain this to me that would be great!

Iam working with Python, fastapi and sqlalchemy although, i do think that i made a mistake with sqlalchemy

My models.py


# User model
class User(_database.Base):
    __tablename__ = "users"
    id = _sql.Column(_sql.Integer, primary_key=True, index=True)
    email = _sql.Column(_sql.String, unique=True, index=True)
    hashed_password = _sql.Column(_sql.String)
    date_created = _sql.Column(_sql.DateTime, default=_dt.datetime.utcnow)

    accounts = _orm.relationship("Account", back_populates="owner")
    trades = _orm.relationship("Trade", back_populates="trades")

    # Function om te checken of het verzonden password matched met het hashed passowrd met bcrypt
    def verify_password(self, password: str):
        return _hash.bcrypt.verify(password, self.hashed_password)


# Account model
class Account(_database.Base):
    __tablename__ = "accounts"
    id = _sql.Column(_sql.Integer, primary_key=True, index=True)
    owner_id = _sql.Column(_sql.Integer, _sql.ForeignKey("users.id"))
    first_name = _sql.Column(_sql.String, index=True)
    last_name = _sql.Column(_sql.String, index=True)
    role = _sql.Column(_sql.String, index=True)
    note = _sql.Column(_sql.String, default="")
    date_created = _sql.Column(_sql.DateTime, default=_dt.datetime.utcnow)
    date_last_updated = _sql.Column(_sql.DateTime, default=_dt.datetime.utcnow)

    owner = _orm.relationship("User", back_populates="accounts")


# Trade Model
class Trade(_database.Base):
    __tablename__ = "trades"
    id = _sql.Column(_sql.Integer, primary_key=True, index=True)
    owner_id = _sql.Column(
        _sql.Integer, _sql.ForeignKey("users.id")
    )  # Krijgt een FK mee zodat een trade bij User kan komen
    trade_id = _sql.Column(
        _sql.Integer, index=True
    )  # Trades die gemaakt zijn hebben een uniek id vanuit exchange
    ticker = _sql.Column(
        _sql.String, index=True
    )  # Welke ticket is de trade gemaakt bv BTC/USDT, DOGE/USDT, etc.
    exchange = _sql.Column(
        _sql.String, index=True
    )  # Op welke exchange is de trade gemaakt
    date_created = _sql.Column(_sql.DateTime, default=_dt.datetime.utcnow)
    trade_note = _sql.Column(
        _sql.String, default=""
    )  # kunnen mensen toevoegen waarom ze een trade zijn ingestrap (Soort logboek)

    trades = _orm.relationship("User", back_populates="trades")

My services.py (The function that throws the error is create_trade(), it is the last one)


async def create_user(user: _schemas.UserCreate, db: _orm.Session):
    user_obj = _models.User(
        email=user.email, hashed_password=_hash.bcrypt.hash(user.hashed_password)
    )
    db.add(user_obj)
    db.commit()
    db.refresh(user_obj)
    return user_obj


async def authenticate_user(email: str, password: str, db: _orm.Session):
    user = await get_user_by_email(db=db, email=email)

    if not user:
        return False

    if not user.verify_password(password):
        return False

    return user


async def create_token(user: _models.User):
    user_obj = _schemas.User.from_orm(user)

    token = _jwt.encode(user_obj.dict(), JWT_SECRET)

    return dict(access_token=token, token_type="bearer")


async def get_current_user(
    db: _orm.Session = _fastapi.Depends(get_db),
    token: str = _fastapi.Depends(oauth2schema),
):
    try:
        payload = _jwt.decode(token, JWT_SECRET, algorithms=["HS256"])
        user = db.query(_models.User).get(payload["id"])
    except:
        raise _fastapi.HTTPException(
            status_code=401, detail="Invalid Email or Password"
        )

    return _schemas.User.from_orm(user)


async def create_trade(
    user: _schemas.User, db: _orm.Session, trade: _schemas.TradeCreate
):
    # **trade.dict() 'unpacked' als het waren de Trade model dus je kan zegegen
    # zelfde als het zeggen trade.owner_id = owner_id, trade.ticker = ticker, etc.

    trade = _models.Trade(**trade.dict(), owner_id=user.id)
    db.add(trade)
    db.commit()
    db.refresh(trade)

    print(f"{user.id} ================")

    return _schemas.Trade.from_orm(trade)


And last but not least my main.py

@app.post("/api/users")
async def create_user(
    user: _schemas.UserCreate, db: _orm.Session = _fastapi.Depends(_services.get_db)
):
    db_user = await _services.get_user_by_email(user.email, db)
    if db_user:
        raise _fastapi.HTTPException(status_code=400, detail="Email already exists")

    await _services.create_user(user, db)

    return await _services.create_token(user)


# Token om toegang te krijgen tot authenticated gedeelte


@app.post("/api/token")
async def generate_token(
    form_data: _security.OAuth2PasswordRequestForm = _fastapi.Depends(),
    db: _orm.Session = _fastapi.Depends(_services.get_db),
):
    # gebruikt email
    user = await _services.authenticate_user(form_data.username, form_data.password, db)

    if not user:
        raise _fastapi.HTTPException(status_code=401, detail="Invalid Credentials")

    return await _services.create_token(user)


# @param me - is als in de authenticated user, hier staat me dus voor
@app.get("/api/users/me", response_model=_schemas.User)
async def get_user(user: _schemas.User = _fastapi.Depends(_services.get_current_user)):
    return user


@app.post("/api/trades", response_model=_schemas.Trade)
async def create_trade(
    trade: _schemas.TradeCreate,
    user: _schemas.User = _fastapi.Depends(_services.get_current_user),
    db: _orm.Session = _fastapi.Depends(_services.get_db),
):
    return await _services.create_trade(user=user, db=db, trade=trade)

schema.py

class AccountCreate(_AccountBase):
    pass


class Account(_AccountBase):
    id: int
    owner_id: int
    date_created: _dt.datetime
    date_late_updated: _dt.datetime

    class Config:
        orm_mode = True


class _TradeBase(_pydantic.BaseModel):
    id: int
    owner_id: int
    trade_id: int
    ticker: str
    exchange: str
    date_created: _dt.datetime
    trade_note: str


# De twee functies hieronder vooralsnog (redundant wordt niks mee gedaan)
class Trade(_TradeBase):
    class Config:
        orm_mode = True

    pass


class TradeCreate(_TradeBase):
    pass

All tips and tricks are welcome! Thank you!

CodePudding user response:

That's what I thought, look here:

trade = _models.Trade(**trade.dict(), owner_id=user.id)

Notice that trade has already owner_id field. That mean you try to pass it twice. You must think do you need owner_id in trade at all. If so, you need to remove one owner_id from there:

trade = _models.Trade(**trade.dict())

or with exclude

trade = _models.Trade(**trade.dict(exclude={"owner_id"}), owner_id=user.id)
  • Related