Django admin foreign key dropdown list with custom value

I have 3 Django models:

class Test(models.Model): pass class Page(models.Model): test = models.ForeignKey(Test) class Question(model.Model): page = models.ForeignKey(Page) 

If I register the Question model for the administrator, I get a drop-down list with the desired Page . Now, what do I need to change to display the desired Page plus this page corresponding to Test ?

Say, if I have three pages, the drop-down menu will contain the following values: Page1 , Page2 , Page3 . I would like to see: Page1 - Test1 , Page2 - Test1 , Page3 - Test1

+9
python django django-admin
source share
1 answer

2 options.

Option 1:

Create a new field , copy forms.ModelChoiceField and override label_from_instance .

 # From the source class PageModelChoiceField(forms.ModelChoiceField(): def label_from_instance(self, obj): """ This method is used to convert objects into strings; it used to generate the labels for the choices presented by this object. Subclasses can override this method to customize the display of the choices. """ # Then return what you'd like to display return "Page{0} - Test{1}".format(obj.pk, obj.test.pk) 

This will only change the text for this particular dropdown field. As you access the Test object for each item in the list, you can provide the queryset you pass. PageModelChoiceField has select_related('test') , otherwise it will do a DB hit for each item in the list.

I did not check this exact code, but there is logic. I'll try later when I can

 class QuestionForm(forms.ModelForm): page = PageModelChoiceField( queryset=Page.objects.select_related('test').all() ) class Meta: model = Page class QuestionAdmin(ModelAdmin): class Meta: model = Question form = QuestionForm 

Option B.

Change the Unicode () Page view.

 class Page(models.Model): test = models.ForeignKey(Test) def __unicode__(self): return "Page{0} - Test{1}".format(obj.pk, obj.test.pk) 

This will change the way the Page displayed wherever you print the page object: print(page_object) , {{ page_object }} .


Personally, I prefer option 1

+11
source share

All Articles