python - 跨 django ManyToManyField 的数据库查询

标签 python django django-database

我想了解如何选择 ManyToMany 字段包含另一个对象的所有对象。我有以下型号(精简)

class Category(models.Model):
    pass

class Picture(models.Model):
    categories = models.ManyToManyField(Category)
    visible = models.BooleanField()

我需要一个函数来选择一个或多个类别中的所有图片:

def pics_in_cats(cat_ids=()):
    pass

但如果可能的话,它需要返回一个查询集,以便我可以执行以下操作:

pics_in_cats((1,2,3)).filter(visible=True)

可以通过加载所有相关的 Category 对象并合并它们的 picture_set 属性来完成,但这似乎效率低下。如果可能的话,我还希望避免退回到原始 SQL。

提前致谢

最佳答案

为什么要编写自定义函数而不使用这样的函数? (未经测试)

pics = Picture.objects.filter(categories__in = [1,2,3]).filter(visible=True)

关于python - 跨 django ManyToManyField 的数据库查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1819613/

相关文章:

python - 对象.filter ("ı wanna add two contains field")

python - Django:为什么当我在 django 中通过 popen 使用 Ghostscript 时,会出现 "file not found"错误

python - Django 管理员未将数据保存到数据库

python - 使用 Python 解析 html

python - 如何根据 URL 列表制作嵌套字典?

python - djangorest-framework单例ViewSet

django - 使用 Amazon API Gateway 时,如何从 Django 后端获取请求中使用的 API key ?

Django : Is it better to set PostgreSQL as database from the start of project?

python - 在 Django View 中使用数据库

python - 陷入 Scapy 文档中的 VarLenQField 示例