在 Django 中使用具有 2 ManyToMany 字段的查询中的过滤器

发布于 2024-10-31 15:00:31 字数 597 浏览 2 评论 0原文

我将尽力描述我在这里要做的事情。 我有 3 个类:

  • Question
  • QuestionType
  • QuestionTemplate

关系是:

  • Question <-ManyToMany-> QuestionType
  • QuestionTemplate <-ManyToMany-> QuestionType

因此,查询位于 QuestionTemplate 内部的方法中,该方法为我提供了可能的问题列表,这些问题具有与 QuestionTemplate 相关的相同 QuestionType。

我尝试过:questions = Question.objects.filter(type__in = template.type.all()) 其中“模板”是 QuestionTemplate 对象。 但此查询返回给我的问题在模板的 QuestionType 列表中至少有一个 QuestionType。 我想要做的是让问题和模板中的 QuestionType 完全相同。

我尝试了很多方法,但无法使其发挥作用,请有人救救我!

I'll try my best to describe what I'm trying to do here.
I have 3 classes:

  • Question
  • QuestionType
  • QuestionTemplate

And the relations are:

  • Question <-ManyToMany-> QuestionType
  • QuestionTemplate <-ManyToMany-> QuestionType

So the query is in a method inside QuestionTemplate that gets me a list of possible questions that have the same QuestionType that are related to the QuestionTemplate.

I've tried:questions = Question.objects.filter(type__in = template.type.all())
Where "template" is a QuestionTemplate object.
But this query returns to me the Questions that have at least one QuestionType inside the QuestionType list from template.
What I want to do is get the have exactly the same QuestionTypes in both question and template.

I tried many things, but cant get this to work, please, somebody save me!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

天煞孤星 2024-11-07 15:00:31
types = template.type.all()
query = Question.objects
for t in types:
    query = query.filter(type = t)
questions = []
for q in query.select_related('type'):
    ok = True
    for t in q.type.all():
        if t not in types:
            ok = False
            break
    if ok:
        questions.append(q)
save_questions_in_m2m_relations_so_that_you_dont_have_to_repeat_this(questions)

相当笨拙,但应该做你需要的事情。

types = template.type.all()
query = Question.objects
for t in types:
    query = query.filter(type = t)
questions = []
for q in query.select_related('type'):
    ok = True
    for t in q.type.all():
        if t not in types:
            ok = False
            break
    if ok:
        questions.append(q)
save_questions_in_m2m_relations_so_that_you_dont_have_to_repeat_this(questions)

Quite clumsy, but should do what you need.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文