0

模型.py

class Types(models.Model):
    user = models.ForeignKey(User, null=True)
    title = models.CharField('Incident Type', max_length=200)
    parent_type_id = models.CharField('Parent Type', max_length=100, null=True, blank=True)
    is_active = models.BooleanField('Is Active', default=True)

上面的视图和表单用于将数据添加到数据库并在模板中显示,复选框动态显示。所以现在我想从数据库中获取这些值并将其显示在另一个页面中。为此,我的 views.py 是

def what(request):
    user = request.user
    type = TypeSelectionForm(type_id)
    types = Types.objects.filter(user=user.id, parent_type_id=None).order_by('title')
    typelist = Types.objects.filter(user=user.id,parent_type_id=type_id).order_by('title')
 #   type = Types.objects.filter(parent_type_id=type_id)
    return render(request, 'incident/what.html',
        {
            'newreport_menu': True,
            'types':types,
            'typelist': typelist,
    })

我正在尝试从数据库中过滤数据并通过上述视图将其显示在另一个页面中,但我不确定我在What视图中使用的代码是否正确,因为它没有给出相关的输出。例如,如果数据库中的值是“学校”它显示输出为[<Types: Types object>, <Types: Types object>] [<Types: Types object>, <Types: Types object>]

4

1 回答 1

1

如果您的问题出在零件上,请向您的模型<Types: Types object>添加一个__unicode__()方法。Types

class Types(models.Model):
    user = models.ForeignKey(User, null=True)
    title = models.CharField('Incident Type', max_length=200)
    parent_type_id = models.CharField('Parent Type', max_length=100, null=True, blank=True)
    is_active = models.BooleanField('Is Active', default=True)

    def __unicode__(self):
        return self.title

    @property
    def parent_types(self):
        """ For accessing the parent types without introducing relationship """
        return self.objects.filter(pk=self.parent_type_id)

这将title在列表中显示对象的 ,而不是<Types: Types object>

更新:我添加了一个属性,这样您就可以在types.parent_types不更改模型的情况下访问父类型。

于 2013-05-28T06:32:54.503 回答