django-ninja icon indicating copy to clipboard operation
django-ninja copied to clipboard

Field with list factory causes API docs to not load with non-serializable.

Open wachpwnski opened this issue 1 year ago • 2 comments

When I use Field(list, alias="model related name") API doc generation no longer works and fails out with an issue with serializing. I'm not sure if this is how I am doing it or if I should make it Optional[List[BookSchema]] in the case that no matching foreign keys exist.

class Author(models.Model):
    first_name = models.CharField(max_length=64)
    last_name = models.CharField(max_length=64)

class Book(models.Model):
    title = models.CharField(max_length=64)
    author = models.ForeignKey(
        Author,
        related_name="books",
        null=False,
        on_delete=models.CASCADE,
    )

class BookSchema(Schema):
    title: str

class AuthorSchema(Schema):
    first_name: str
    last_name: str
    books: List[BookSchema] = Field(list, alias="books")  # Causes an error in API docs

wachpwnski avatar Mar 29 '24 02:03 wachpwnski

@wachpwnski

try:

class AuthorSchema(Schema):
    ...
    books: List[BookSchema] = Field([], alias="books") 

vitalik avatar Mar 29 '24 15:03 vitalik

@wachpwnski

try:

class AuthorSchema(Schema):
    ...
    books: List[BookSchema] = Field([], alias="books") 

This fixed my issue. Thank you!

wachpwnski avatar Mar 30 '24 09:03 wachpwnski