python - 使用过滤器和排除来过滤对象及其实例

标签 python django django-models

我正在尝试这样过滤:

#models.py
class A(models:Model):
    all_letters = models.ManyToManyField(Letters, related_name="all_letters")
    selected_letters = models.ManyToManyField(Letters, related_name="selected_letters")
#views.py
a = A.objects.get(pk=pk)
array_one = a.all_letters.all().exclude(a.selected_letters.all())

我知道你不能根据实例进行过滤,但这是使用某种手动 python 搜索来执行此操作的唯一等效方法吗?

最佳答案

您可以过滤掉反向关系(您将其命名为selected_letters)不指向a的项目,因此:

array_one = a.all_letters.exclude(<b>selected_letters=a</b>)

关于python - 使用过滤器和排除来过滤对象及其实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66535845/

相关文章:

python - 寻找方程的自洽解

python - 类型错误 : tuple indices must be integers or slices, 不是 str

python - 属性错误 : module 'django.db.models' has no attribute 'MultiPolygonField'

python - 如何从 InlineFormset 中的图像字段获取图像 URL?

python - 在 Wagtail 中实现文章和页面模型之间的一对多

python - Pandas 将两列值添加到新数据框

python - 使用嵌套的可写序列化程序上传 django rest 框架文件

python - 在 python 中打印长整数

python - 使用 python 2.5 安装 django,而不是使用默认版本的 python

Django "The submitted file is empty"