同名车型的Pydantic列表

时间:2019-12-11 11:06:28

标签: python python-3.x pydantic

假设我要创建一个User模型,该模型还包含必须是用户列表的“ friends”字段:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    packagingOptions {
        exclude 'META-INF/DEPENDENCIES.txt'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/dependencies.txt'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/LGPL2.1'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/notice.txt'
    }

    defaultConfig {
        applicationId "com.abc.xyz"
        minSdkVersion 16
        targetSdkVersion 16
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}
repositories { mavenCentral() }

dependencies {
    compile 'com.google.android.gms:play-services:7.3.0'
    compile 'com.android.support:support-v4:21.0.3'
    compile 'com.google.code.gson:gson:2.3.1'
    compile files('libs/volley.jar')
    compile 'com.facebook.android:facebook-android-sdk:4.0.0'
    compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5'
    compile (group: 'org.apache.httpcomponents' , name: 'httpmime' , version: '4.3.6') {
        exclude module: 'org.apache.httpcomponents:httpclient'
    }
}

但这是不可能的。有没有办法实现这种行为?

1 个答案:

答案 0 :(得分:0)

是的,您需要使用update_forward_refs,请参阅文档中的self-referencing models

from typing import List

from devtools import debug

from pydantic import BaseModel


class User(BaseModel):
    id: int
    name: str
    friends: List['User']


User.update_forward_refs()

u = User(id=123, name='hello', friends=[dict(id=321, name='goodbye', friends=[])])

debug(u)

输出:

test.py:18 <module>
    u: User(
        id=123,
        name='hello',
        friends=[
            User(
                id=321,
                name='goodbye',
                friends=[],
            ),
        ],
    ) (User)