python - 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?
解决方案
您可以将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()
这种方法的好处是你几乎不需要改变你的模型结构。
推荐阅读
- reactjs - Material-UI withStyles 不向道具添加类
- powershell - 如何通过按 Escape 来逃脱读取主机?
- ms-access - 过滤不同表单的不同查询字段
- git - Git 分支中引入的提交差异
- aws-lambda - 如何使用 micronaut-function-aws-api-proxy 处理多部分/表单数据文件上传
- javascript - 如何使用 history.push 在 React 中获取参数
- java - 我如何将此代码放入 4 种方法(矩阵加法、矩阵减法、矩阵乘法矩阵除法)和一个主要方法(称为驱动程序)
- cocoapods - 为什么 pod 目标构建设置 Swift 语言版本号不同,我们如何在 Xcode 中修复?
- javascript - 在使用云托管时,程序代码是否比编译后的 javascript 中的面向对象代码快得多?
- oracle - 如何在 oracle sql 中获取日文格式的日期(2008 年 12 月 31 日)