我正在寻求一些关于如何针对多个对象执行查询并在其关联对象的详细视图中一起使用它们的建议。这是我现在正在使用的内容:
-- 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 %}
我希望尽可能避免那些难以在产品寿命期内维护的黑客攻击。再次感谢你们的帮助 =)