[Answered ]-How to create field with information from another field

1πŸ‘

βœ…

I would advise to calculate the name on-demand, like:

from random import choices


class CompanyUserPhysicalCard(models.Model):
    def company_card_code(self):
        letters = '01234567890QLUBOK'
        return ''.join(choices(letters, k=6))

    card = models.ForeignKey(
        Cards,
        on_delete=models.CASCADE,
        related_name='company_physical_user_cards',
    )
    company = models.ForeignKey(
        Company, on_delete=models.SET_NULL, null=True, verbose_name='компания'
    )
    _custom_id = models.CharField(
        max_length=6, default=company_card_code, editable=False, blank=True
    )

    @property
    def custom_id(self):
        return f'{self._custom_id}{self.company.company_name}'

We thus generate the code prefix, and when we need it, we append the company name.

If the company later changes its name, for example 'Facebook' to 'Meta', without having to alter the table, it will also change the custom_id.

You can filter by concatenating with ConcatΒ [Django-doc], for example:

from django.db.models.functions import Concat

CompanyUserPhysicalCard.objects.alias(
    custom_id=Concat('_custom_id', 'company__company_name')
).filter(custom_id='123456GOOGLE')

Leave a comment