'Django model's __str__ with seperate fields
I have a model that return's a financial year and a description. Currently the attributes are combined into one value as one field.
As you can see, the year 2021 and description test. I can click on the field which brings me to the details page.
My code:
class Meta:
ordering = ['description', 'accounting_year', 'swift_code']
verbose_name_plural = "Extractions"
def __str__(self):
return f'{self.accounting_year} {self.description}'
What I would like to achieve, but can't figure out nor find it online is to split the two fields into separate columns. Thus, 2021 as a column and test as a column.
Furthermore, I would like to be able to sort or even filter, because one of the fields is extraction date. Would be great that an admin user could changed the order from newest to oldest and vice versa of just filter on name or date. Any documentation on that?
Solution 1:[1]
Try saving the role first and then add it to Org and then save the Org:
Organization created = save(organization);
Role role = new Role();
role.setCode("test");
save(role); // this assign a persistant primary key to the role
created.getRoles().add(role);
return save(created);
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 | Juliyanage Silva |

