Fixes #23799 squashmigrations optimize conditionally

This commit fixes this issue
https://code.djangoproject.com/ticket/23799

It has tests and implementation