python - 查询多个 Django 模型

标签 python django generic-foreign-key multi-table-inheritance

我正在寻找一些关于如何针对多个 对象执行查询然后在相关对象的详细 View 中一起使用它们的建议。这是我现在正在处理的内容:

-- 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

我想要完成的是在类别详细信息 View 中同时显示两者 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 %}

如果可能的话,我想远离难以在该产品的生命周期内维护的hack。再次感谢你们的帮助 =)

最佳答案

对于 manager_that_queries_both.all 您可以使用 Django Model Utils .

特别是 Inheritance Manager .

您的外键将引用基类。然后你可以查询它们

Material.objects.select_subclasses()

要根据对象的类型在模板中执行操作,您可以实现描述的过滤器 here .

关于python - 查询多个 Django 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21209182/

相关文章:

python - 单线检查列表中的至少一项是否存在于另一个列表中?

python - Django select_lated 查询不会将所有值返回到模板

python - 过滤通用外键

python - 在仍然理智的情况下在 Django 中设置通用外键

python - 如何录制内部音频? Python

python - Tensorflow 损失没有减少并且准确度停留在 0.00%?

python - 尝试在 Shopify 上发布请求时,请求出现 400 错误

textarea标签内的Django模板换行符

django - 在 Django 中上传和读取 xlsx 文件

python - update_or_create 的 Django GenericRelation