Search code examples
djangodjango-rest-frameworkdjango-serializer

In Django ModelSerializer unable to mark a field required as false


I am trying to make a field investor required as False in Django Restframework's ModelSerializer.

class WatchListSerializer(serializers.ModelSerializer):

    class Meta:
        model = WatchList
        fields = ['id', 'investor', 'property']
        extra_kwargs = {
            'investor' : {
                'required' : False
            }
        }

However, both the fields are defined as ForeignKeys in the model. As you can see in above implementation I am trying to override the default implementation of field investor using extra_kwargs. Unfortunately, it still asking to provide the value for investor.

Here is the model Watchlist -

class WatchList(BaseModel):

    investor = models.ForeignKey(User, on_delete=models.PROTECT, blank=False, null=True)
    property = models.ForeignKey(Properties, on_delete=models.PROTECT, blank=False, null=True)

    class Meta:
        
       unique_together = (('investor', 'property',))

    def __str__(self):
        
        return f'Watch List Object {self.id}:'


Solution

  • With the blank=… parameter [Django-doc], you specify whether the field is required in a ModelForm, ModelAdmin, ModelSerializer and other parts of the code that process data into a model object.

    You thus can disable this with:

    class WatchList(BaseModel):
        # …
        property = models.ForeignKey(
            Properties,
            on_delete=models.PROTECT,
            blank=True,
            null=True
        )