我正在尋找如何對多個執行查詢對象,然後在其相關對象的詳細視圖一起使用他們一些建議。以下是我與現在的工作:查詢多個Django模型
-- 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 %}
我想從黑客那將是難以維持的,如果有可能該產品的壽命望而卻步。再次感謝您的幫助球員=)
哇,謝謝你的及時響應。我有點不確定的一件事就是如何根據檢索的模型類型動態地在模板中顯示這些結果。希望這是有道理的! –
我添加了一個指向過濾器的鏈接,可以使用該類名(無需向模型添加方法) –