问题
I have a many to many field and a foreign key field on a model form. It appears to be making the right query but the result are Objects and not the values of the object.
Do I need to overwrite the queryset using a VALUES_LIST method?
forms.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: ')
}
models.py
class AccountParameters(models.Model):
acctFilterName = models.ForeignKey(AccountFilters)
excludeClassification = models.ManyToManyField(ClassificationNames)
tradingCash = models.FloatField()
回答1:
You have to add a method to represent your object with a string :
If you are using python 2, use __unicode__
and on python 3 use : __str__
.
E.g (with 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 (with 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
来源:https://stackoverflow.com/questions/33818717/django-model-form-many-to-many-field-is-not-displaying-value