Reputation: 967
I have been studying and playing around with django with my test app and I would like to request assistance regarding this matter.
I have the following models:
class Job_Posting(models.Model):
Job_Position = models.CharField(max_length=30, null=True, unique=True)
def __unicode__(self):
return self.Job_Position
class Courses_list(models.Model):
Abbreviation = models.CharField(max_length=100, unique=True)
Course = models.CharField(max_length=100, unique=True)
def __unicode__(self):
return self.Abbreviation
class Educational_Requirement(models.Model):
fkey = models.ForeignKey('Job_Posting')
Course = models.ForeignKey('Courses_list')
This is pretty much straight forward in the admin, adding job posts and assigning the course required. My problem is with the Educational_Requirement
because I am displaying it in my frontend via form's ModelChoiceField
and overriding the queryset
to display the right choices.
The dropdown display's Educational_Requirement object
and I want it to display the value of Course
in Educational_Requirement
. I can't use __unicode__
in Educational_Requirement
as it returns an error:
coercing to Unicode: need string or buffer, Courses_list found
Do I really need to set the __unicode__
in the Educational_Requirement
and add the string field? I can't do it because it would really break the purpose of why I did it or is there a better way to implement this? Many thanks.
Feel free to comment if you have any tips for a newbie and it would be greatly appreciated.
Upvotes: 0
Views: 145
Reputation: 25539
If you want to change the display value for ModelChoiceField
, you could easily define your own field and override label_from_instance
method:
class CourseField(forms.ModelChoiceField):
def label_from_instance(self, obj):
# return the field you want to display, which is Course
return obj.Course
class EducationalRequirementForm(forms.ModelForm):
Course = CourseField(queryset=Courses_list.objects.all())
Not related, but your are suffering from some poor coding styles. Models are python classes, so they should be like EducationalRequirement
. Fields are python class attributes, they should be lower case with underscores like job_position
. Check python PEP8 documentation for more code style information.
Upvotes: 1