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

`DataclassJSONField` implementation

Open ghost opened this issue 3 years ago • 6 comments

as discussed in https://github.com/bhch/django-jsonform/issues/75

WIP WIP WIP

Example

@dataclass
class MyDataclass(JsonSchemaMixin):
    id: int
    whatever: str


class MyModel(TimestampedModel):
    single = DataclassJSONField(MyDataclass, null=True)
    many = DataclassJSONField(MyDataclass, many=True, blank=True, default=list)

image

In [1]: m = MyModel.objects.first()

In [2]: m.single
Out[2]: MyDataclass(id=123, whatever='123')

In [3]: m.many
Out[3]: [MyDataclass(id=123, whatever='123'), MyDataclass(id=456, whatever='456')]

In [4]: m.single.whatever='hello'

In [5]: m.many[0].whatever='world'

In [6]: m.many.pop()
Out[6]: MyDataclass(id=456, whatever='456')

In [7]: m.save()

In [8]: m = MyModel.objects.first()

In [9]: m.single
Out[9]: MyDataclass(id=123, whatever='hello')

In [10]: m.many
Out[10]: [MyDataclass(id=123, whatever='world')]

ghost avatar Nov 07 '22 22:11 ghost

@bhch , I'm unsure if this should become it's own package django-dataclass-field. Thoughts?

ghost avatar Nov 08 '22 15:11 ghost

FYI: I am @ghost. I had to delete my other account for logistics reasons.

I'm starting to lean towards making a separate package because I don't have time to investigate and support older Python/Django versions.

My next step is to fix the "required" fields, because on Admin, I can't submit empty for fields like x: int | None

dongyuzheng avatar Nov 11 '22 16:11 dongyuzheng

@bhch does your library support json schema with anyOf? https://stackoverflow.com/questions/35450405/how-to-represent-sum-union-types-in-in-json-schema

Edit:

Looks like No. It fails here

image

dongyuzheng avatar Nov 11 '22 16:11 dongyuzheng

Currently, anyOf doesn't work but it will be added (#39). I can't seem to come up with a good approach to create forms for anyOf/allOf/oneOf.

I'm starting to lean towards making a separate package because I don't have time to investigate and support older Python/Django versions.

That's understandable. I'd like to avoid breaking changes until the next major release (v3).

bhch avatar Nov 11 '22 17:11 bhch

Another question @bhch , I noticed that the Django admin form sends Empty String for empty integer field, rather than null

I know this is probably because it's hard to tell the difference between null and no input and empty string.

One thing Swagger UI does is they have a tick box [] Send empty value to indicate sending a null.

Thoughts on adding this to the Form?

dongyuzheng avatar Nov 11 '22 18:11 dongyuzheng

@dongyuzheng Okay, I'll add something similar to that. I've just created an issue for this: #78

bhch avatar Nov 11 '22 19:11 bhch