Django ModelChoiceFieldsQuetyset不从db返回实际值 [英] Django ModelChoiceField queryset does not return actual values from db

查看:141
本文介绍了Django ModelChoiceFieldsQuetyset不从db返回实际值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型是:

My models are:

class ActionType(models.Model):


    id_action_type = models.FloatField(primary_key=True)
    action_name = models.CharField(max_length=15, blank=True, null=True)


    class Meta:
        managed = False
        db_table = 'action_type'

class TicketsForm(models.Model):
    ticket_id = models.FloatField(primary_key=True)
    ticket_type = models.CharField(max_length=30, blank=True, null=True)
    action_type = models.CharField(max_length=15,blank=True, null=True)

在我的表单中我有:

In my forms i have:

class BankForm(forms.ModelForm):

    action_type= forms.ModelChoiceField(queryset=ActionType.objects.all(),widget=forms.RadioSelect)

    class Meta:
        model = TicketsForm
        fields = ('ticket_type',
                  'action_type',)

当这个呈现为html时,我看不到 ActionType.objects.all()的实际值,而是看到

ActionType对象

RadioButton附近的ActionType对象
任何人都可以告诉我我的错误在哪里。

When this is rendered to html i Don't see the actual values of ActionType.objects.all() but instead i see
ActionType object
ActionType object near RadioButton. Can anyone tell me where my mistake is.

推荐答案

你需要定义一个 __ str__ 方法。例如:

You need to define a __str__ method for your model. For example:

from django.utils.encoding import python_2_unicode_compatible

@python_2_unicode_compatible
class ActionType(models.Model):
    id_action_type = models.FloatField(primary_key=True)
    action_name = models.CharField(max_length=15, blank=True, null=True)

    ...

    def __str__(self)
        return self.action_name

只有使用Python 2,才需要使用 python_2_unicode_compatible decorator。请参阅 __ str __ 文档以获取更多信息。

The python_2_unicode_compatible decorator is only required if you are using Python 2. See the __str__ docs for more info.

这篇关于Django ModelChoiceFieldsQuetyset不从db返回实际值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆