在 Django 中过滤类和子类

发布于 2024-07-25 10:30:18 字数 478 浏览 2 评论 0原文

我有一个带有常见问题解答应用程序的项目。 该应用程序具有常见问题解答(由网站作者编写)和用户常见问题解答(由用户编写 - 不仅仅是一个聪明的名称)的模型。 我想返回符合特定条件的所有条目、FAQ 或 UserFAQ,但我也想排除任何不符合特定条件的 UserFAQ。 理想情况下,它看起来像:

faqs = FAQ.objects.filter(question__icontains=search).exclude(show_on_site=False)

其中“show_on_site”是只有 UserFAQ 对象才具有的属性。 这不起作用,因为过滤器会在父类上崩溃,因为它不拥有该属性。 这样做的最佳方法是什么? 我遇到了 这个片段,但这对于我想做的事情来说似乎有点矫枉过正。

I have a project with an FAQ app. The app has models for FAQ (written by the site authors) and UserFAQ (written by users-- not just a clever name). I want to return all entries, FAQ or UserFAQ that match certain conditions, but I also want to exclude any UserFAQs that don't match a certain criteria. Ideally, it would looks something like:

faqs = FAQ.objects.filter(question__icontains=search).exclude(show_on_site=False)

Where "show_on_site" is a property that only UserFAQ objects have. That doesn't work because the filter craps out on the parent class as it doesn't posses the property. What's the best way of doing this? I came across this snippet, but it seems like overkill for what I want to do.

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

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

发布评论

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

评论(1

眼眸印温柔 2024-08-01 10:30:18

在您的位置,不需要有两个表,我会很想拥有一个带有 is_user_faq 和 show_on_site 字段的常见问题解答模型/表。

有时,在对数据进行建模以组织数据以便简单、快速访问时它会有所帮助。 虽然模型继承有一些吸引力,但我发现避免使用它通常更容易。

In your position, absent a need to have two tables, I'd be tempted to have one FAQ model/table with is_user_faq and show_on_site fields.

Sometimes it helps when modeling data to organize it for simple and fast access. While model inheritance has some appeal, I've found it it's often easier to avoid using it.

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