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

ModelSchema: related objects

Open pedro-prose opened this issue 3 years ago • 2 comments

Hi, is there support for related objects in ModelSchema?

With the following Django model:

class Example(Model):
    hash =models.CharField(max_length=255)
    version = models.ForeignKey('core.Version', on_delete=models.CASCADE, null=True, db_index=False)

I have a version object:

In [1]: Version.objects.get(version='0.0.1').id
Out[1]: 10001

But defining a schema like the following:

class ExampleSchema(ModelSchema):
    class Config:
        model = Example
        model_fields = ['hash', 'version']

    @pydantic.validator('hash', check_fields=False, pre=True)
    def pre_hash(cls, hash):
        return hash + '_fake_hash'

    @pydantic.validator('version', check_fields=False, pre=True)
    def pre_version(cls, version):
        try:
            version = Version.objects.get(version=version).id
        except Version.DoesNotExist:
            return None
        return version

I'll always get the related object as None.

In [2]: RecommendationSchema(hash='dasdasxs', version='0.0.1')
Out[2]: RecommendationSchema(hash='dasdasxs_fake_hash', version=None)

pre_hash is always called. pre_version is never called.

Thank you.

pedro-prose avatar Jan 27 '22 21:01 pedro-prose

Edit: by explicitly declaring the version attribute, I get the object. Shouldn't models.ForeignKey be supported without explicit declaration of the field?

class ExampleSchema(ModelSchema):
    version: str

    class Config:
        model = Example
        model_fields = ['hash', 'version']

    @pydantic.validator('hash', check_fields=False, pre=True)
    def pre_hash(cls, hash):
        return hash + '_fake_hash'

    @pydantic.validator('version', check_fields=False, pre=True)
    def pre_version(cls, version):
        try:
            version = Version.objects.get(version=version).version
        except Version.DoesNotExist:
            return None
        return version
In [2]: RecommendationSchema(hash='dasdasxs', version='0.0.1')
Out[2]: RecommendationSchema(hash='dasdasxs_fake_hash', version='0.0.1')

Thanks.

phbernardes avatar Jan 27 '22 21:01 phbernardes

Same issue here,

omidraha avatar Jul 20 '22 11:07 omidraha