如何形成数据以供选择?

时间:2019-04-29 14:06:18

标签: django django-forms django-templates

有一个模型Provider。它具有字段role,该字段具有两个选项:IndividualOrganization。有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))

1 个答案:

答案 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