Django模型表单多对多字段不显示值

时间:2015-11-20 03:56:05

标签: python django django-models django-forms

我在模型表单上有多个字段和一个外键字段。它似乎正在进行正确的查询,但结果是对象而不是对象的值。

我是否需要使用VALUES_LIST方法覆盖查询集?

forms.py

Yii::$app->user->id = $my_userid;

models.py

    class Meta:
    model = AccountParameters
    fields =['acctFilterName', 'excludeClassification', 'tradingCash',]
    #exclude = ['acctFilterName']
    labels = {
        'acctFilterName': _('Account Filters:'),
        'excludeClassification': _('Exclude Classifications: '),
        'tradingCash':_('Remove accounts whose trading cash < % of AUM: ')
    }

Screenshot of multiselect

1 个答案:

答案 0 :(得分:0)

您必须添加一个方法来用字符串表示您的对象:

如果您使用的是python 2,请使用__unicode__并在python 3上使用:__str__

E.g(使用python 2):

class AccountFilters(models.Model):
    name = models.CharField(max_length=255)
    # other attributes

    def __unicode__(self):
        return self.name

class AccountParameters(models.Model):
    acctFilterName = models.ForeignKey(AccountFilters)
    excludeClassification = models.ManyToManyField(ClassificationNames)
    tradingCash = models.FloatField()

    def __unicode__(self):
        return self.acctFilterName.name

E.g(使用python 3):

class AccountFilters(models.Model):
    name = models.CharField(max_length=255)
    # other attributes

    def __str__(self):
        return self.name

class AccountParameters(models.Model):
    acctFilterName = models.ForeignKey(AccountFilters)
    excludeClassification = models.ManyToManyField(ClassificationNames)
    tradingCash = models.FloatField()

    def __str__(self):
        return self.acctFilterName.name