Display full names in Form ChoiceField but saving ID's

给你一囗甜甜゛ 提交于 2019-12-12 05:05:11

问题


I have model Person - from another database I copied all person_id to custom_id.

models.py

class Employee(models.Model):
    custom_id = models.CharField(max_length=20, unique=True)

    @property
    def person(self):
        return Person.objects.get(person_id='%s' % self.custom_id)

    def __str__(self):
        return '%s' % self.custom_id

class Task(models.Model):
    employee = models.ManyToManyField(Employee, blank=True, null=True)
    task = models.CharField(max_length=100)
    comment = models.CharField(max_length=200)

    def __str__(self):
        return '%s' % self.task

I add my method person() to Employee which allow me to access other objects model in another database:

So basically when I type this in shell:

Employee.objects.get(custom_id='123').person.full_name

u'Adam Dylan'

I have a ModelForm which use ModelMultipleChoiceField

forms.py

class TaskCreateForm(forms.ModelForm):

    employee = forms.ModelMultipleChoiceField(queryset=Employee.objects.all())

    class Meta:
        model = Task

But Employee.objects.all() returns bunch of custom_id's. What I want is to show in form "Employee(..).person.full_name" but saving only custom_id's.


回答1:


I am not sure why you think the answer I gave to your other question does not work here. Did you try the following? If it does not work, how exactly does it fail?

class EmployeeMultipleChoiceField(ModelMultipleChoiceField):
    def label_from_instance(self, obj):
        return obj.person.full_name

class TaskCreateForm(forms.ModelForm):
    employee = EmployeeMultipleChoiceField(queryset=Employee.objects.all())

    class Meta:
        model = Task


来源:https://stackoverflow.com/questions/31053098/display-full-names-in-form-choicefield-but-saving-ids

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!