'How do I concatenate 2 fields from a related table in a Django Filter Form?
I have 2 models, Composer and Piece with a one-to-many relationship (one composer has many pieces).
I have a form filter that gives 2 dropdown controls from which to select Composer and Instrumentation (from the Piece model) in order to filter the pieces belonging to the selected composer.
The Composer dropdown only shows the surname of the composer, which is really confusing when you have a number of generations of composer in the same family e.g. J.S. Bach, C.P.E Bach etc. The dropdown filter control only shows multiple instances of the surname Bach so the user has no idea which is which. Is it possible to show each composer in the dropdown as "surname, firstName"?
The filter is as follows:
import django_filters
from .models import Piece
class PieceFilter(django_filters.FilterSet):
class Meta:
model = Piece
fields = ['composer', 'instrumentation']
I am only importing the Piece model as composer is a related table but I think I probably need to also import the Composer table but not sure. Any help would be greatly appreciated.
Solution 1:[1]
This was easy after someone showed me. All I needed to do was to add the following to the composer model:
def __str__(self):
return self.surname +', '+ self.name
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Michael Piraner |
