3

我正在尋找如何對多個執行查詢對象,然後在其相關對象的詳細視圖一起使用他們一些建議。以下是我與現在的工作:查詢多個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 %} 

我想從黑客那將是難以維持的,如果有可能該產品的壽命望而卻步。再次感謝您的幫助球員=)

回答

2

對於manager_that_queries_both.all可以使用Django Model Utils

具體的Inheritance Manager

你的外鍵會參照基類。然後你就可以查詢他們

Material.objects.select_subclasses() 

要取決於過濾器描述here你可以實現對象的類型做的事情在你的模板。

+0

哇,謝謝你的及時響應。我有點不確定的一件事就是如何根據檢索的模型類型動態地在模板中顯示這些結果。希望這是有道理的! –

+0

我添加了一個指向過濾器的鏈接,可以使用該類名(無需向模型添加方法) –

1
class SomeObject(Content): 
    # model_specific_arttributes 
    is_some_object = True 

class SomeOtherObject(Content): 
    is_some_object = False 

現在你可以使用if報表模板和兩種類型的對象來區分使用不同的模板來顯示它們。