首页 > 解决方案 > Django .objects,get for merged querysets from different models

问题描述

I have an abstract base model ('Base') from which two models inherit: 'Movie' and 'Cartoon'. I display a list of both movies and cartoons to the user (with the help of itertools.chain). Then I want to give the user the opportunity to delete any of these items, without knowing in advance whether it is a movie or a cartoon. I am trying to do it like this:

        ...

        movies = Movie.objects.filter(user_created=userlist).order_by('title')
        cartoons = Cartoon.objects.filter(user_created=userlist).order_by('title')

        all_items = list(chain(movies, cartoons))

        item = all_items.get(id=item_id)
        item.delete()

But then PyCharm states,

Unresolved attribute reference 'get' for class 'list'

I understand why this happens but I don't know how to avoid it. Is there any way to merge two querysets from different models and apply get or filter without removing the abstract base model and creating a physical parent model?

标签: pythondjangodjango-modelsdjango-querysetdjango-filters

解决方案


您可以将ContentTypes 框架用于针对任意数量的不同模型的通用且可重用的解决方案。但我也想知道为什么Cartoon而且Movie必须从不同的类型开始;可能值得花一点时间考虑是否可以对两种类型的媒体使用单一模型 - 删除任意实例只是单一模型比依赖 ContentTypes 之类的东西更直接的众多情况之一。

编辑:有关 ContentTypes 的更多信息。您可以创建具有通用关系的基本模型(您说您不想这样做),或者对于删除,您可以在请求数据中与项目 ID 一起包含应用标签和模型名称,从而启用如下查找:

    media_type = ContentType.objects.get(app_label=app_label, model=model_name)
    instance = media_type.get_object_for_this_type(id=item_id)
    instance.delete()

这种方法的好处是你几乎不需要改变你的模型结构。


推荐阅读