SeaQL / sea-orm

🐚 An async & dynamic ORM for Rust
https://www.sea-ql.org/SeaORM/
Apache License 2.0
7.3k stars 513 forks source link

Example for deriving Model with default / nullable values #474

Closed VaZark closed 2 years ago

VaZark commented 2 years ago

The following code fails when used as the id field is not part of the InputTask.Is there a way to use Default::default() for an entity model when transforming from another Struct defined for input type. I'm trying to create a generic From so that I can reuse the idea with different models

#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Deserialize, Serialize)]
#[sea_orm(table_name = "tasks")]
pub struct Model {
    #[sea_orm(primary_key)]
    pub id: i32,
    pub title: String,
    pub text: String,
}

#[derive(Serialize, Deserialize)]
struct InputTask {
    pub title: String,
    pub text: String,
}

impl From<InputTask> for Model {
    fn from(a: InputTask) -> Self {
        let serialised = serde_json::to_string(&a).unwrap();
        serde_json::from_str(&serialised).unwrap()
    }
}

Basically I want to avoid doing the below transformation as a part of the application logic

let new_task = task::Model {
        title: Set(payload.title),
        text: Set(payload.text),
        ..Default::default()
    };
billy1624 commented 2 years ago

Hey @VaZark, see https://www.sea-ql.org/SeaORM/docs/advanced-query/custom-active-model

VaZark commented 2 years ago

Thanks! That was exactly what I needed.

The custom active model seems like the closest thing to a Serializer from Django/DRF.

Do you reckon that each Model can have a Model.asInputModel() that autogenerates the base model just without the field marked as _primarykey as default?

billy1624 commented 2 years ago

The concept of InputModel has been discussed in #101