'DRF ModelSerializer meta extra_kwargs not working for related fields

I am developing an API in DRF and have stumbled upon one issue that hopefully you can help me to solve. Let's assume I have the following model and a serializer:

class SomeModelBase(models.Model):
    property = models.ForeignKey(
        Property,
        on_delete=models.PROTECT,
    )
    name = models.CharField()
    address = models.OneToOneField(null=True, blank=True)

class SomeModel(SomeModelBase):
    ...more fields


class SomeModelBaseSerializer(serializers.ModelSerializer):
    
    
    class Meta:
        fields = "__all__"
        model = SomeModelBase
        extra_kwargs = {"address": {"required": True},}


class SomeModelSerializer(SomeModelBaseSerializer):

    class Meta:
        model = SomeModel
        fields = "__all__""
        extra_kwargs = {
            "name": {"required": True},
            "address": {"required": False},
        }

As you can see I am trying to add field kwargs by using extra_kwargs. The issue is that it won't work for a related field e.g. property or address field. I know I can just override it by defining a field manually and passing required=True, and that works but it's too long for my use case. Do you have any idea why this happen and how could i possibly modify required in each child class? Thanks.



Solution 1:[1]

I think you don't need to upload a foreign key object. You'd better add foreign key fields like property_id or address_id instead of using those objects directly.

So you can define that field in the serializer class.

class SomeModelSerializer(serializer.ModelSerializer):
    property_id = serializers.IntegerField(write_only=True, required=True)
    address_id = serializers.IntegerField(write_only=True, required=True)
    
    class Meta:
        model = SomeModel
        fields = "__all__"
        extra_kwargs = {
            "name": {"required": True},
        }

Solution 2:[2]

I have managed to find the answer in the DRF documentation. I didn't mention that my serializers have some manually declared fields and this is the reason as per DRF documentation:

Please keep in mind that, if the field has already been explicitly declared on the serializer class, then the extra_kwargs option will be ignored.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 David Lu
Solution 2 psky