Django ModelChoiceField 查询集不 return 来自数据库的实际值

Django ModelChoiceField queryset does not return actual values from db

我的模型是:

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)

在我的表格中我有:

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 object
ActionType object 单选按钮附近。 谁能告诉我我的错误在哪里。

您需要为您的模型定义一个 __str__ 方法。例如:

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 时才需要 python_2_unicode_compatible 装饰器 2. 有关详细信息,请参阅 __str__ 文档。

我想这是因为您没有在 ActionType 模型上定义 __str__(self)__unicode__(self) 方法。有关详细信息,请参阅 https://docs.djangoproject.com/en/1.9/ref/models/instances/#str

不过,我强烈建议在 TicketsFormActionType 中使用外键。另外,我不确定什么需要定义您自己的私钥;如果你不定义这些,Django 会为你生成它们。有关详细信息,请参阅教程(尤其是 https://docs.djangoproject.com/en/1.9/intro/tutorial02/ 模型)。