Rawkymonk
Rawkymonk

Reputation: 53

Created by field in a user's sub class

I need to have a "created_by" field in the sub user model which will show the User, who created Translator's account (is_translator=True).

User model:

class User(AbstractUser):
    is_client = models.BooleanField('Client status', default=False)
    is_translator = models.BooleanField('Translator status', default=False)

Sub user:

class Translator(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)

Upvotes: 0

Views: 28

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477190

You create an extra ForeignKey [Django-doc]:

class Translator(models.Model):
    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE,
        limit_choices_to={'is_translator': True}
        primary_key=True
    )
    created_by = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='created_translators'
    )

In the view(s) where you create a Translator, you will then need to fill in the created_by field with the logged in user (request.user).


Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Upvotes: 1

Related Questions