Skip to content

Django: Instance vs Class access of attributes should return different types #4080

Description

@bayangan1991

Describe the Bug

Take an example model

class Contact(models.Model):
    address = models.CharField(max_length=200)

When accessing the type from an instance we get the correct str return

item = Contact(address="123 Fake St")
reveal_type(item.address) # revealed_type: str

But when accessing the class attribute we gain access to the FieldDescriptor which lets access metadata about the field.

For example:

class ContactUpdatePayload(pydantic.BaseModel):
    new_address: Annotated[
        str,
        pydantic.Field(max_length=Contact.address.field.max_length), # error: Object of class `str` has no attribute `field` Did you mean `find`?
    ]

reveal_type(Contact.address) # revealed_type: str
# expected: django.db.models.fields._FieldDescriptor[django.db.models.fields.CharField[str | int | django.db.models.expressions.Combinable, str]]

reveal_type(Contact.address.field.max_length) # revealed_type: Unknown
# expected: int | None

Ideally the type should be different when accessing the field via the instance vs the class

Sandbox Link

No response

(Only applicable for extension issues) IDE Information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    djangopydanticIssues related to support for Pydantic

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions