我正在寻找一些关于如何对多个对象执行查询的建议,然后在相关对象的详细视图中将它们一起使用。下面是我现在正在做的工作:
-- 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 %}
我想远离黑客,如果可能的话,这种产品将很难维护一辈子。再次感谢你们的帮助
发布于 2014-01-18 20:16:10
对于manager_that_queries_both.all
,您可以使用Django模型Utils。
特别是遗产管理人。
外键将引用基类。然后,您可以用
Material.objects.select_subclasses()
要在模板中做一些事情,取决于对象的类型,您可以实现描述的这里过滤器。
发布于 2014-01-18 20:38:58
class SomeObject(Content):
# model_specific_arttributes
is_some_object = True
class SomeOtherObject(Content):
is_some_object = False
现在,您可以在模板中使用if
语句来区分这两种类型的对象,并使用不同的模板来显示它们。
https://stackoverflow.com/questions/21209182
复制相似问题