Skip to content

[BUG] Unexpected Behavior of ModelSchema for fields with default #366

@bertraol

Description

@bertraol

Description

Hey, it's me again.

Creating schema instances from an empty dictionary generates values for fields that have a default defined.

Maybe i misunderstand how ModelSchemas are supposed to work, but I perceive this as unexpected behavior.

Expected behavior would be that ValidationError is raised if I don't provide valid values for non-optional fields, but apparently some values magically appear.

See example code below.

I stumbled over this, because I applied ModelSchemas for incoming requests and I wondered why some requests went through which should have failed. After again reading the documentation very carefully - it seems to me that ModelSchema is not recommended for request validation. If that's the case I think it should be made much clearer, maybe even disallow request validation with ModelSchema?

Model

import random
import string
import uuid
from django.db import models

def generate_rnd_string():
    return ''.join(random.choice(string.ascii_lowercase) for i in range(8))

class MyModel(models.Model):
    some_datetime = models.DateTimeField(null=True)
    just_a_uuid = models.UUIDField(default=uuid.uuid4, editable=False)
    random_string = models.CharField(
        default=generate_rnd_string,
        max_length=8,
        null=False
    )
    string_without_default = models.CharField(
        null=True,
        max_length=8,
    )

Schema

from pydantic.types import UUID
from myapp.models import MyModel

class MyModelSchema(ModelSchema):
    class Config:
        model = MyModel
        model_fields = [
            "some_datetime",
            "just_a_uuid",
            "random_string",
            "string_without_default",
        ]

Test code

from django.test import TestCase
from myapp.schemas import MySchema, MyModelSchema

class ModelSchemaBehaviorTest(TestCase):
    def test_modelschema(self):
        modelschema_instance = MyModelSchema(**{})
        print(modelschema_instance.__dict__)

Result

{'just_a_uuid': UUID('42f3fe65-74f2-4d24-b83f-8841a58573c9'),
 'random_string': 'gcgnmjnc',
 'some_datetime': None,
 'string_without_default': None}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions