How to use include/exclude with lists?
See original GitHub issueQuestion
When using include/exclude with nested structures, how do I specify what to include/exclude when the child model is a list?
Where the child is a single element and I only want the id of that element, I know from the docs that I can do:
A.dict(include={"id": ..., "child": {"id": ...}})
Where the child is a list of a model, and I only want a single element of that list, and only the id of that element, I know from reading #640 that I can do:
A.dict(include={"id": ..., "children": {0: {"id": ...}}})
But what is the syntax (assuming there is a syntax) to specify that I want all children, but only the “id” field for all children?
Also, what would be the syntax (again, assuming it is possible) to specify that for the Parent, I want all top level attributes, but only the “id” of the nested attributes?
Thank you for your help and for the library.
Please complete:
- OS: Linux
- Python version
import sys; print(sys.version)
: 3.7.4 - Pydantic version
import pydantic; print(pydantic.VERSION)
: 1.0
Please read the docs and search through issues to confirm your question hasn’t already been answered.
Where possible please include a self contained code snippet describing your question:
from __future__ import annotations
from typing import List, Optional
from pydantic import BaseModel, VERSION as pydantic_version
from dataclasses import dataclass
class Parent(BaseModel):
id: int
child: Child
children: List[Child] = []
class Config:
orm_mode = True
class Child(BaseModel):
id: int
age: int
class Config:
orm_mode = True
Parent.update_forward_refs()
@dataclass
class OrmChild:
id: int
age: int
@dataclass
class OrmParent:
id: int
children: List[OrmChild]
child: OrmChild
c1 = OrmChild(1, 12)
c2 = OrmChild(2, 7)
c3 = OrmChild(3, 2)
a = OrmParent(id=1, children=[c1, c2, c3], child=c1)
A = Parent.from_orm(a)
print(A.dict(
# WHAT GOES HERE?!
)
Issue Analytics
- State:
- Created 4 years ago
- Reactions:6
- Comments:11 (4 by maintainers)
I can only assume what other people would commonly require but I think
This is something I expect people to want quite commonly - more commonly than wanting to have just the _n_th element of a list, which was one of the test cases you discussed when developing the syntax.
The reason I want this is for an API, with nested models, some of which are quite large, I only want to send to the front end the top level attributes and a subset of children elements to be fetched if required. I think this is also quite commonly needed in APIs, but it is not my area of expertise.
answering my question: the error occurs in pydantic version 1.8.2. When updated to version 1.9.0 everything went fine ! cheers