Inverted Inheritance Structure in Pydantic

I know the normal way of creating Models in Pydantic is by Subclassing and adding fields for example like this:

from pydantic import BaseModel

class Base(BaseModel):
    task_id: str
    task_type: int

class UserCreationTask(Base):
    username: str
    firstname: str
    lastname: str

class  UserInfoTask(Base):
    address: str
    email: str
    phone: str

However I have the following problem. I’ve defined a set of Models to represent my data in mongodb. These models define all attributes a document can have inside a collection. Following the additive approach as above, I would have to create my DBModels as a union of all request models plus some hidden fields.

I would like to invert this structure. Make the request models inherit from the DB and define fields which should be excluded from everything (both schema generation, schema validation and schema serialization). Basically make it as if it has never been defined.

I haven’t found a neat way to do it. I’m not inheriting at the moment and I’m just redefining the fields ad nausium.

class DBTask(BaseModel):
    task_id: str
    task_type: int

    username: str
    firstname: str
    lastname: str

    address: str
    email: str
    phone: str

class ReqUserCreation(BaseModel):
    task_id: str
    task_type: int

    username: str
    firstname: str
    lastname: str

class ReqUserInfo(BaseModel):
    task_id: str
    task_type: int

    address: str
    email: str
    phone: str

I’ve been able to create the Inverted Inheritance Structure like this:

class Hide(object):
    def __new__(cls):
        if not hasattr(cls, 'instance'):
            cls.instance = super(Hide, cls).__new__(cls)
        return cls.instance


def hide_attributes(cls: Type[BaseModel]):
    for attr_name, attr_type in cls.__annotations__.items():
        if attr_type is Hide:
            cls.__annotations__[attr_name] = Optional[None]
            setattr(cls, attr_name, Field(default=None, exclude=True))
    return cls

class DBTask(BaseModel):
    task_id: str
    task_type: int

    username: str
    firstname: str
    lastname: str

    address: str
    email: str
    phone: str

# Version 4
@hide_attributes
class ResponseTask(DBTask):
    # Version 2:
    address: str = Field(exclude=True)
    email: str = Field(exclude=True)
    phone: str = Field(exclude=True)

    # Version 3
    address: Optional[None] = Field(exclude=True, default=None)
    email: Optional[None] = Field(exclude=True, default=None)
    phone: Optional[None] = Field(exclude=True, default=None)

    # Version 4
    address: Hide 
    email: Hide
    phone: Hide

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Version 1
        del self.address
        del self.email
        del self.phone

    model_config = ConfigDict(
        populate_by_name=True,
        arbitrary_types_allowed=True,
    )
Version 1

This works however, the fields are still present in the documentation of the model in FastAPI and the fields are still required in during model_validate

Version 2

Here the problem is, that we still have to provide the Model with the email, phone and address during model_validation. I don’t want this to be the case. The fields is no longer in the serialized output as well as the documentation.

Version 3

This version works but it’s super verbose and I’m not that big of a fan.

Version 4

This technically works. However the order of operations prevents this from working. The decorator is applied after the parsing? using Pydantic. So even tho the model afterwards has all Attributes of type Hide changed to Optional[None] and it’s value set to Field(default=None, exclude=True) but the parsing? of the object with Pydantic has already taken place i.e. Pydantic is applied before the decorator so it still expects all attributes regardless.

Ideally, I want a solution using a decorator that works like the exclude={...}, exclude_none, exclude_unset, include in the model_dump. So my code would look something like this:

@decorator(hide={"address", "email", "phone"})
class SomeModel(SomeDBModel):
    pass

But I’m not sure whether that’s possible.

Thank you for your help.

AliSot2000

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật