# coding: utf-8

from django.db import models
from django.db.models.fields import related_descriptors
from django.utils.functional import cached_property


class ExistingOnlyManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().filter(is_deleted=False)


class SoftDelete(models.Model):
    is_deleted = models.BooleanField(default=False, editable=False)

    def delete(self, **kwargs):
        self.is_deleted = True
        self.save(update_fields=('is_deleted',))

    class Meta:
        abstract = True


class ReverseManyToOneDescriptor(
    related_descriptors.ReverseManyToOneDescriptor
):
    @cached_property
    def related_manager_cls(self):
        related_model = self.rel.related_model

        return related_descriptors.create_reverse_many_to_one_manager(
            related_model._base_manager.__class__, self.rel
        )


class ForeignKey(models.ForeignKey):
    related_accessor_class = ReverseManyToOneDescriptor
