有一个模型Provider
。它具有字段role
,该字段具有两个选项:Individual
和Organization
。有summary
字段和organization
字段。
在form
(在模板中)(模板)中,在select
中,必须以以下方式显示数据:如果记录与Individual
,然后是summqry + user
,如果使用Organization
,则是Organization title
。
models.py
ROLE_INDIVIDUAL = 'individual'
ROLE_ORGANIZATION = 'organization'
ROLE_CHOICES = (
(ROLE_INDIVIDUAL, _('Individual')),
(ROLE_ORGANIZATION, _('Organization'))
)
class Provider(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
role = models.CharField(max_length=255, choices=ROLE_CHOICES, default=ROLE_INDIVIDUAL)
summary = models.CharField(max_length=255, default='')
organization = models.ForeignKey(Organization, on_delete=models.CASCADE)
forms.py
class ProductCreateForm(forms.ModelForm):
class Meta:
model = Product
fields = (..., 'on_behalf', ...)
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('initial').get('request')
super(ProductCreateForm, self).__init__(*args, **kwargs)
self.fields['on_behalf'] = ModelChoiceField(queryset=Provider.objects.filter(user=user.id))
答案 0 :(得分:2)
您应该在Provider上定义__str__
方法以返回所需的字符串。
class Provider(models.Model):
...
def __str__(self):
if self.role == ROLE_INDIVIDUAL:
return '{} + {}'.format(self.summary, self.user)
else:
return self.organization.title