This looks like a bug in Django REST Framework (DRF) 3.16.0, where the UniqueConstraint
might be affecting field serialization. In DRF 3.15.2, the foo
field was included, but in DRF 3.16.0, it disappears.
foo
in Meta.fields
Since foo
is being removed when using UniqueConstraint
, you can explicitly list it in Meta.fields
:
class BaseModelSerializer(ModelSerializer): foo = SerializerMethodField() class Meta: model = None # Override in subclasses fields = ("id", "foo", "bar") # Explicitly include `foo` @staticmethod def get_foo(obj) -> int | None: return obj.foo
2. Useextra_kwargs
to Force Inclusion
Another workaround is using extra_kwargs
in the serializer:
class BaseModelSerializer(ModelSerializer): class Meta: model = None # Override in subclasses
fields = ("id", "foo", "bar"
) extra_kwargs = {"foo": {"read_only": True}}
foo
in to_representation
If the issue persists, override to_representation
to ensure foo
is serialized:
class BaseModelSerializer(ModelSerializer): class Meta: fields = ("id", "bar") # Exclude `foo` here to manually add def to_representation(self, instance): data = super().to_representation(instance) data["foo"] = instance.foo # Ensure `foo` is added back return data
--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-fram...@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/django-rest-framework/7922c7ed-15b2-4544-b6a7-c959df9af55an%40googlegroups.com.