我正在寻找一些关于如何针对多个 对象执行查询然后在相关对象的详细 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/