oxan / djangorestframework-dataclasses

Dataclasses serializer for Django REST framework
BSD 3-Clause "New" or "Revised" License
431 stars 28 forks source link

Nested dataclasses and using drf-spectacular. #52

Closed macsikora closed 2 years ago

macsikora commented 2 years ago

Hey, I am using this great lib and found problems with drf-spectacular. These are my issues:

If I have nested dataclass like:

@dataclass
class A():
   foo: str

class B():
   a: A

# serializer 
class BSerializer(DataclassSerializer):
  class Meta:
    dataclass = B

# the same results with  DataclassSerializer(B)

Then final docs do not recognise fields of A saying: object (Dataclass)

When I try:

# serializer 
class BSerializer(DataclassSerializer):
  a = DataclassSerializer(A)
  class Meta:
    dataclass = B

It does not give any effect, I still have a: object (Dataclass)

In order to have it working I need to define for every nested dataclass its own empty serializer like:

class ASerializer(DataclassSerializer):
   class Meta:
     dataclass = A

class BSerializer(DataclassSerializer):
  a = ASerializer()
  class Meta:
    dataclass = B

What gives a lot of such proxy code (imagine few such dataclasses inside) Also docs print all the time comment from the DataclassSerializer, so I see :

object (Dataclass)A DataclassSerializer is just a regular Serializer, except that:A set of default fields are automatically populated.A set of default validators are automatically populated.Default .create() and .update() implementations are provided.The process of automatically determining a set of serializer fields based on the dataclass fields is slightly complex, but you almost certainly don't need to dig into the implementation.If the DataclassSerializer class doesn't generate the set of fields that you need you should either declare the extra/differing fields explicitly on the serializer class, or simply use a Serializer class.

For every field using DataclassSerializer.

In summary using these two things together looks like quite a struggle.

oxan commented 2 years ago

See #28 and #41. There's not much about this that can be fixed from our side, drf-spectacular needs to be changed for this to work.

macsikora commented 2 years ago

Hey @oxan tnx very much. Do you know if there is already some traction, issue created on their side?

oxan commented 2 years ago

I don't know.

oxan commented 2 years ago

Oops, closed wrong issue with that commit.

oxan commented 2 years ago

See https://github.com/tfranzel/drf-spectacular/pull/639.

macsikora commented 2 years ago

many thanks @oxan !

oxan commented 2 years ago

I'll close this, as that PR has been merged now. You can manually include that extension in your project until drf-spectacular has a new release.