Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you reference a model name in a Django model mixin field definition?

How do you reference the model name in field definition in a model mixin? Ie, what would replace model_name here:

class CreatedByMixin(models.Model):

    class Meta:
        abstract = True

    created_by = ForeignKey(
        User,
        verbose_name="Created by",
        help_text="User that created the record",
        related_name=f"{model_name}_created",
        editable=False,
    )

Such that the related name on this model is ‘MyModel_created’?

class MyModel(UserAuditMixin, TimeStampedModel):
    class Meta:
        db_table_comment = "Participants are the users that are involved in the transcript"

    field1 = models.TextField()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are looking for %(class)s [Django-doc]. You don’t format the string in the ForeignKey: Django automatically (re)formats the string, so you use:

class CreatedByMixin(models.Model):
    class Meta:
        abstract = True

    created_by = ForeignKey(
        User,
        verbose_name='Created by',
        help_text='User that created the record',
        related_name='%(class)s_created',
        editable=False,
    )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading