How can I specify certain fields as optional?

21 views Asked by At

When making a PATCH request, I want to make my model fields optional, excluding the date.

My model looks like this,

class Units(models.TextChoices):
    KILOGRAM = 'kg', _('Kilogram')
    POUND = 'lbs', _('Pound')


class Weights(models.Model):
    class Meta:
        unique_together = ('date', 'user_id')  # Do not allow multiple weight entries for the same day.

    date = models.DateField()
    weight = models.DecimalField(max_digits=5, decimal_places=2, validators=[MinValueValidator(1)])
    unit = models.CharField(choices=Units.choices, max_length=3)

    user_id = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return f'On {self.date}, you weighed {self.weight}{self.unit}'

My Serializer is this,

class WeightTrackingRequest(ModelSerializer):
    class Meta:
        model = Weights
        fields = ('date', 'weight', 'unit')

My View is this,

    @swagger_auto_schema(request_body=WeightTrackingRequest)
    def patch(self, request):
        """
        Updates an existing weight for a particular date.
        """

My question is, how can I state that I want the "date" field to be required, but the unit and weight fields to be optional. As of now, swagger is stating that they're both required in the generated documentation.

I do not want these fields optional in my model, only when making a PATCH.

0

There are 0 answers