BeanieODM / beanie

Asynchronous Python ODM for MongoDB
http://beanie-odm.dev/
Apache License 2.0
2.04k stars 215 forks source link

[BUG] Mypy not validating query with `Link` field #368

Closed dlionel closed 1 year ago

dlionel commented 2 years ago

Describe the bug When making query with related elements, mypy raise an attribut error for related fields. Even a field as obvious as id is flagged with an error.

To Reproduce

Create a file: test_beanie_link.py

import beanie

class Merchant(beanie.Document): 
    pass

class Review(beanie.Document): 
    merchant: beanie.Link[Merchant]

async def list_reviews()-> None:
    merchant = await Merchant.find_one()
    assert merchant
    Review.find_many(Review.merchant.id == merchant.id)
    review = Review(merchant=merchant)

Then run:

mypy test_beanie_link.py

Expected behavior Expecting mypy to run without issue raised.

Instead got:

test_beanie_link.py:15: error: "Link[Merchant]" has no attribute "id"
test_beanie_link.py:16: error: Argument "merchant" to "Review" has incompatible type "Merchant"; expected "Link[Merchant]"

Additional context

LinuxKernel31 commented 1 year ago

There's something wrong with how you structured it.

Merchant should have atleast 1 field, mypy will detect it because it has no attribute id and you're accessing the id Field.

Also judging by the query you're using, you should be using it this way: bar = await Review.find_one(Review.merchant.id == merchant.id)

from typing import Optional
from beanie import Link
from pydantic import Field
import beanie

class Merchant(beanie.Document): 
    id = Field(None, alias="_id")

class Review(beanie.Document): 
    merchant: Optional[Link[Merchant]]

async def list_reviews()-> None:
    merchant = await Merchant.find_one()
    assert merchant
    Review.find_many(Review.merchant.id == merchant.id)
    review = Review(merchant=merchant)

Try this one.

github-actions[bot] commented 1 year ago

This issue is stale because it has been open 30 days with no activity.

github-actions[bot] commented 1 year ago

This issue was closed because it has been stalled for 14 days with no activity.