Skip to content

Instantly share code, notes, and snippets.

@andrewtremblay
Last active March 30, 2023 16:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewtremblay/94c485f816f3095d7e86668b97b1a668 to your computer and use it in GitHub Desktop.
Save andrewtremblay/94c485f816f3095d7e86668b97b1a668 to your computer and use it in GitHub Desktop.
Django classes that help you create a common model for your database.
from django.db import models
from django.conf import settings
from rest_framework import viewsets, serializers
class CommonModel(models.Model):
"""Common fields that are shared among all models."""
created_by = models.ForeignKey(settings.AUTH_USER_MODEL,
editable=False, related_name="+")
updated_by = models.ForeignKey(settings.AUTH_USER_MODEL,
editable=False, related_name="+")
created_at = models.DateTimeField(auto_now_add=True,
editable=False)
updated_at = models.DateTimeField(auto_now=True,
editable=False)
class CommonViewSet(viewsets.ModelViewSet):
"""Ensure the models are updated with the requesting user."""
def perform_create(self, serializer):
"""Ensure we have the authorized user for ownership."""
serializer.save(created_by=self.request.user, updated_by=self.request.user)
def perform_update(self, serializer):
"""Ensure we have the authorized user for ownership."""
serializer.save(updated_by=self.request.user)
class CommonSerializer(serializers.ModelSerializer):
"""Ensure the fields are included in the models."""
common_fields = ['created_by', 'created_at', 'updated_by', 'updated_at']
# CAVEAT 1:
# If using a custom user model, add the following line to the top:
# from api.models.user_profile import User # noqa: F401
# It's needed for get_model in settings.
# CAVEAT 2:
# All api calls that add or edit a line to your database should be Authenticated.
# If you're not doing that then you are ASKING for trouble.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment