在 Django 中过滤类和子类
我有一个带有常见问题解答应用程序的项目。 该应用程序具有常见问题解答(由网站作者编写)和用户常见问题解答(由用户编写 - 不仅仅是一个聪明的名称)的模型。 我想返回符合特定条件的所有条目、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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的位置,不需要有两个表,我会很想拥有一个带有 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.