Python Django-按属性将查询划分为子组
我有一个这样的模型:Python Django-按属性将查询划分为子组,python,django,django-queryset,choicefield,Python,Django,Django Queryset,Choicefield,我有一个这样的模型: class ListEntry(models.Model): STATUS_CHOICES = ( ('PL', _('Playing')), ('CO', _('Completed')), ('OH', _('On-hold')), ('DR', _('Dropped')), ('WA', _('Want to play')), ) user = models.Fore
class ListEntry(models.Model):
STATUS_CHOICES = (
('PL', _('Playing')),
('CO', _('Completed')),
('OH', _('On-hold')),
('DR', _('Dropped')),
('WA', _('Want to play')),
)
user = models.ForeignKey(User)
game = models.ForeignKey(Game)
status = models.CharField(_('Status'), max_length=2,
choices=STATUS_CHOICES)
class GameListByUserView(ListView):
model = ListEntry
template_name = 'game_list_by_user.html'
def get_queryset(self):
self.user_profile = get_object_or_404(User, username=self.kwargs['slug'])
return ListEntry.objects.filter(user=self.user_profile)
def get_context_data(self, **kwargs):
context = super(GameListByUserView, self).get_context_data(**kwargs)
context['user_profile'] = self.user_profile
return context
在我的视图中,我按用户筛选条目,如下所示:
class ListEntry(models.Model):
STATUS_CHOICES = (
('PL', _('Playing')),
('CO', _('Completed')),
('OH', _('On-hold')),
('DR', _('Dropped')),
('WA', _('Want to play')),
)
user = models.ForeignKey(User)
game = models.ForeignKey(Game)
status = models.CharField(_('Status'), max_length=2,
choices=STATUS_CHOICES)
class GameListByUserView(ListView):
model = ListEntry
template_name = 'game_list_by_user.html'
def get_queryset(self):
self.user_profile = get_object_or_404(User, username=self.kwargs['slug'])
return ListEntry.objects.filter(user=self.user_profile)
def get_context_data(self, **kwargs):
context = super(GameListByUserView, self).get_context_data(**kwargs)
context['user_profile'] = self.user_profile
return context
我现在尝试的是根据status
属性将此查询(ListEntry.objects.filter(user=self.user\u profile)
)拆分为子组,因此呈现的模板如下所示:
UserFoo's list
=========================
Playing
Game 1
Game 2
Game 3
Completed
Game 4
Game 5
Game 6
我知道我可以做一些事情,比如:
q = ListEntry.objects.filter(user=self.user_profile)
games_dict = {}
games_dict['playing'] = q.filter(status='PL')
games_dict['completed'] = q.filter(status='CO')
依此类推,并迭代模板中的键。或(在模板中):
但是,没有更好的优化方法来实现这一点,而不必每次按状态获取子查询时都访问数据库,也不必多次迭代对象列表吗?您正在寻找
{%按状态将对象列表重新组合为游戏列表%}
{游戏中游戏的%u列表%}
- {{game.gropper}
{game.list%中项目的%s}
- {{item}}
{%endfor%}
{%endfor%}
您可能需要自定义元素的渲染方式,但我会让您自己来解决这个问题