【发布时间】:2017-05-27 15:25:50
【问题描述】:
我正试图弄清楚如何添加一个包含另一个表中的计数的字段。
我有一个带有“项目”的表格和另一个带有“任务”的表格。任务具有项目的外键。
models.py
class Item(MPTTModel):
item_title = models.CharField(max_length=250)
item_parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)
class Task(models.Model):
task_title = models.CharField(max_length=550)
item = models.ForeignKey('item.Item')
以及我进行查询并希望在每行项目中添加一列计数的视图。
views.py
def index(request):
all_root_items = Item.objects.filter(item_parent__isnull=True)
context = {
'nodes': all_root_items ,
}
return render(request, 'tasks/index.html', context)
所以我希望 all_root_items 中的每个项目都有一个字段(例如“task_count”)。这是分配给该项目的任务数。
我尝试了很多不同的想法。但没有一个有效。
编辑以澄清我的问题。
all_root_item 看起来像这样
items [
{"item_title" : "item 1", "item_parent" : ""},
{"item_title" : "item 2", "item_parent" : ""}
]
我想为每个项目添加任务计数。所以它看起来像这样
items [
{"item_title" : "item 1", "item_parent" : "", "task_count" : "6"},
{"item_title" : "item 2", "item_parent" : "", "task_count" : "2"}
]
【问题讨论】:
-
您想在管理员或模板中显示?
-
@hansTheFranz 在模板中。
标签: django django-views