[Answered ]-How to show and use only days in datetime in DRF model fields and send requests to fill the field

1👍

you can override the to_representation(self, value) method. This method takes the target of the field as the value argument, and should return the representation that should be used to serialize the target. The value argument will typically be a model instance.

To get days from timedelta use .days property.

serializer.py

class ReservationDetailSerializer(serializers.ModelSerializer):
    reservation_days = serializers.SerializerMethodField('get_reservation_days_list')

    class Meta:
        model = Reservation
        fields = (
            'id', 'reservation_type', 'office', 'workplaces',
            'initial_day', 'days_delta', 'reservation_days', 'user'
        )

    def to_representation(self, instance):
        change_fields = ( 'days_delta', )
        data = super().to_representation(instance)

        for field in change_fields:
            try:
                data[field] = field.days
            except Exception as e:
                print(e)
        return data 
                
    def get_reservation_days_list(self, reservation_model):
        initial_day = reservation_model.initial_day
        days_delta = reservation_model.days_delta
        reservation_days = []

        for delta in range(days_delta.days):
            reservation_days.append(date.isoformat(initial_day + timedelta(days=delta)))

        return reservation_days


    def validate(self, validated_data):
        validated_data['days_delta'] = validated_data['days_delta'] * 86400

        if validated_data['reservation_type'] == 'office':
            workplaces = []
            for workplace in Workplace.objects.all().filter(office=validated_data['office']):
                workplaces.append(workplace.pk)
            validated_data['workplaces'] = workplaces

        return validated_data
👤Sohaib

Leave a comment