查询多个Django模型

3

我正在寻求一些关于如何针对多个对象执行查询并在其关联对象的详细视图中一起使用它们的建议。这是我现在正在使用的内容:

-- app/models.py --

class Material(models.Model):
  created = models.DateTimeField(auto_now_add=True)
  updated = models.DateTimeField(auto_now=True)
  title = models.CharField(max_length=50)
  slug = models.SlugField()
  description = models.TextField()

  def __str__(self):
    return self.title

class Category(Material):
  parent = models.ForeignKey('self', related_name='children')

class Content(Material):
  author = models.ForeignKey(User)
  category = models.ForeignKey(Category)

class SomeObject(Content):
  # Model specific properties and methods

class SomeOtherObject(Content):
  # Model specific properties and methods

我想实现的目标是在类别详细视图中同时显示SomeObject和SomeOtherObject。这两个模型都有不同的属性,使它们彼此独特。这种情况下,使用通用外键是否有用?
-- app/templates/category_detail.html --

{% block content %}
  <header class="category-header">
    <h1 class="category-title">{{ category.title }}</h1>
  </header><!-- .category-header -->

  <section class="category-items">
    {% for item in category.manager_that_queries_both.all %}
      # Display each item differently depending on the type
    {% empty %}
      "Oops, we couldn't find anything for this category!"
    {% endfor %}
  </section><!-- .category-items -->
{% endblock %}

我希望尽可能避免那些难以在产品寿命期内维护的黑客攻击。再次感谢你们的帮助 =)
2个回答

2
对于 manager_that_queries_both.all,您可以使用Django Model Utils。具体来说,是使用Inheritance Manager。您的外键应该指向基类,然后可以使用以下查询语句进行查询。
Material.objects.select_subclasses()

如果您想根据对象类型在模板中执行操作,可以实现此处描述的过滤器。


哇,感谢您及时的回复。有一件事我有点不确定,那就是如何根据检索到的模型类型动态地在模板中显示这些结果。希望这样说得清楚! - Chris Shelton
我添加了一个链接到一个过滤器,让你可以使用类名(而不必向你的模型添加方法)。 - Daniel Rucci

1
class SomeObject(Content):
    # model_specific_arttributes
    is_some_object = True

class SomeOtherObject(Content):
    is_some_object = False

现在你可以在模板中使用if语句来区分两种类型的对象,并使用不同的模板来显示它们。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接