Auto-populating BaseModel fields Django model

42 Views Asked by At

I have a base model class which is:

class BaseModel(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='%(class)s_createdby', null=True,
                                   blank=True, on_delete=models.DO_NOTHING)
    updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='%(class)s_updatedby', null=True,
                                   blank=True, on_delete=models.DO_NOTHING)

    class Meta:
        abstract = True

And all my objects extend this parent class. I want it to automatically adjust the data for created_by and updated_by whenever user .save() the objects(either create or update). And I don't want to manually pass the user every time.

I'm using graphene and here's an example where I adjust the object and I don't want to pass the updated_by manually.

class CreateWorkspace(graphene.Mutation):
    workspace = graphene.Field(WorkspaceType)

    class Arguments:
        name = graphene.String(required=True)
        description = graphene.String(required=False)

    @login_required
    def mutate(self, info, name, description):
        workspace = Workspace(name=name, description=description)
        return CreateWorkspace(workspace=workspace)

Is there any automated way of doing it without the need to add a code for each subclass?

0

There are 0 best solutions below