3

挑战,在嵌套中输出一个单选选择<ul></ul>,按任务 fk 分组。

IE。

class Category(models.Model):
    # ...

class Task(models.Model):
    # ...
    category = models.ForeignKey(Category)
    # ...

表格.py

class ActivityForm(forms.ModelForm):
    # ...
    task = forms.ModelChoiceField(
        queryset    = Task.objects.all(),
        widget      = RadioSelectGroupedByFK
    )

小部件.py

class RadioFieldRendererGroupedByFK(RadioFieldRenderer):
    """
    An object used by RadioSelect to enable customization of radio widgets.
    """
    #def __init__(self, attrs=None):
        # Need a radio select for each?? Just an Idea.
        #widgets = (RadioSelect(attrs=attrs), RadioSelect(attrs=attrs))
        #super(RadioFieldRendererGroupedByFK, self).__init__(widgets, attrs)

    def render(self):
        """Outputs nested <ul> for this set of radio fields."""
        return mark_safe(
            #### Somehow the crux of the work happens here? but how to get the
            #### right context??
            u'<ul>\n%s\n</ul>' % u'\n'.join(
                [u'<li>%s</li>' % force_unicode(w) for w in self]
            )
        )

class RadioSelectGroupedByFK(forms.RadioSelect):
    renderer = RadioFieldRendererGroupedByFK

最好的感谢!

4

1 回答 1

1

itertools.groupby()非常适合这个。我会假设每个都有一个Task你希望它们排序的属性。我不知道 Django API,因此您可能希望将排序转移到 db 查询中,并且您需要查看小部件的属性以了解如何访问任务对象,但这是基本公式:Categoryname

from itertools import groupby

# sort first since groupby only groups adjacent items
tasks.sort(key=lambda task: (task.category.name, task.name))

for category, category_tasks in groupby(tasks, key=lambda task: task.category):
  print '%s:' % category.name
  for task in category_tasks:
    print '* %s' % task.name

这应该打印一个列表,如:

Breakfast foods:
* eggs
* spam
Dinner foods:
* spam
* spam
* spam

高温高压

于 2009-03-25T08:29:32.457 回答