[Answered ]-Django REST-framework: Making a field optional

2👍

In your serializer you can mark your fields as not required by passing required arguments as False

class UserResponse(ModelSerializer):
    response = IntegerField()
    meta_data = MetaDataSerializer(allow_null=True, required=False)

0👍

Based on Django REST framework manual

Field-level validation

You can specify custom field-level validation by adding
.validate_ methods to your Serializer subclass. These are
analogous to .clean_ methods on Django forms, but accept
slightly different arguments.

They take a dictionary of deserialized attributes as a first argument,
and the field name in that dictionary as a second argument (which will
be either the name of the field or the value of the source argument to
the field, if one was provided).

So, the Solution is to create a list validation method like this:

def validate_list(self, attrs, source):
    """
    Check that the list is correct or not?
    """
    if list not in attrs:
        list_item = TodayList.objects.create()
        list = list_item.id
    return attrs

Another solution is in the model level, by overriding the save() and check the list id.

def save(self, *args, **kwargs):
    if self.list is None:
        self.list = TodayList.objects.create()
    super(TodayListItem, self).save(*args, **kwargs) # Call the "real" save() method.
👤Othman

Leave a comment