我正在寻找一些关于如何对多个对象执行查询然后在相关对象的详细视图中一起使用它们的建议。这是我现在正在使用的内容:
-- 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 %}
如果可能的话,我想远离在该产品的整个生命周期内难以维护的黑客攻击。再次感谢你们的帮助=)