Company with many different names
I have the following situation that looks simple, but I do not know how to make models for it :(
Here is what I have.
Model Company that contains only description (field note)
class Company(models.Model):
note = models.TextField(_('note'), blank=True, null=True)
class Meta:
verbose_name = _('Company')
def __str__(self):
return f'{self.id}'
Each company can have many different names (Official Name, Short Name, Long Name, etc.) I have model CompanyName for it.
class CompanyName(models.Model):
company = models.ForeignKey(Company, related_name='name_set')
type = models.CharField(_('type'), max_length=4, choices=NameType.choices)
name = models.CharField(_('name'), max_length=256)
class Meta:
verbose_name = _('Company name')
def __str__(self):
return f'{self.type} {self.name}'
The issue I have:
How inside Company model get 'Official Name' from CompanyName Model. I would like to use the official name instead of f'{self.id}'
inside __str__
function.
Thank you so much for your help and time,
You get it with a .filter(type='Official Name')
:
class Company(models.Model):
note = models.TextField(_('note'), blank=True, null=True)
class Meta:
verbose_name = _('Company')
def __str__(self):
official = self.name_set.filter(type='Official Name').first()
if official:
return f'{official.name}'
return f'{self.id}'