Задать вопрос
VladimirZhid
@VladimirZhid
Нравится делать что-то интересное и полезное.

Как реализовать обратную связь из потомков абстрактной модели с помощью фреймворка contenttypes?

Всем мир и с наступающим!
И так товарищи, вопрос таков:

Имеется абстрактная модель "PostAbstract" и в каждом разделе сайта имеется наследуемая от "PostAbstract", в дальнейшем их я буду называть просто постами. В "корневом" апе есть модели Photo и Video, которые уже связанны с постами. Для данной связи я использую фреймворк contenttypes, правда не могу придумать как реализовать обратную связь из постов к Photo и Video, т.к описывать поле GenericRelation в абстактной модели нельзя.

root/models.py
class Post(models.Model):
    """Base class of Post on site"""

    sources = []

    def __init__(self, *args, **kwargs):
        # "Owner"(owner) is required field! You can define that in instances of this class
        if "owner" not in vars(self.__class__):
            raise Exception("Field \"owner\" is undefined!")
        else:
            super().__init__(*args, **kwargs)

    # meta information
    create_date = models.DateField(auto_now_add=True)
    modify_date = models.DateField(auto_now=True)

    description = models.TextField()
    size = models.PositiveSmallIntegerField(
        editable=False, default=0, verbose_name="Колличество вложенностей")

    def create_photo(self, description, src, file):
        photo = Photo(description=False,
                      src=src,
                      file=file,
                      content_object=self
                      )
        photo.save()
        return photo

    def create_video(self):
        pass

    def get_sources(self):
        photos = Photo.objects.get(content_object=self)
        print(photos)
        pass

    def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
        return super(Post, self).save()

    class Meta:
        abstract = True
class Photo(models.Model):
    # GenericForeignKey Felds
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.BigIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')
    # meta information
    create_date = models.DateField(auto_now_add=True)
    modify_date = models.DateField(auto_now=True)
    # Main Fields
    description = models.TextField(null=True, blank=True)
    src = models.CharField(max_length=500, blank=True)
    file = models.FileField(null=True, blank=True)

    class Meta:
        unique_together = (("object_id", "src"),)


class Video(models.Model):
    # GenericForeignKey Felds
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.BigIntegerField()
    content_object = GenericForeignKey()
    # meta information
    create_date = models.DateField(auto_now_add=True)
    modify_date = models.DateField(auto_now=True)
    # Main Fields
    description = models.TextField()
    src = models.CharField(max_length=500, blank=True)
    file = models.FileField(null=True, blank=True)

    class Meta:
        unique_together = (("object_id", "src"),)


films/models.py
# модель наследуемая от root.models.Post
class MoviePost(Post):
    owner = models.ForeignKey(Movie, on_delete=models.CASCADE)


Есть у вас какие-нибудь идеи и сталкивался кто-либо с подобным? Заранее спасибо, если не понятно что-то, то комментируйте
  • Вопрос задан
  • 171 просмотр
Подписаться 1 Оценить Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы