Knowledge Base: Django Generic Fields

Summary
Guidelines and Answers to all things Django Generic Fields
Status
Published
Created On
Nov 14, 2023 2:47 AM
Updated On
Nov 14, 2023 7:33 AM

Knowledge Base: Django Generic Fields

β€£
{{ page_properties }}

How To…

β€£

Create a Generic Field

from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType

class Message(models.Model):
	author_content_type = models.ForeignKey(
        ContentType,
        on_delete=models.CASCADE,
        related_name="messages",
    )
    author_object_id = models.UUIDField()
    author = GenericForeignKey(
        "author_content_type",
        "author_object_id"
    )
		...

β€£

Limit a Generic Field to specific models

from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType

class Message(models.Model):
		author_content_type = models.ForeignKey(
	      ContentType,
	      on_delete=models.CASCADE,
	      related_name="messages",
				limit_choices_to={
	          "model__in": [
	              "agent",
	              "customer"
	          ]
	      }
	  )
	  author_object_id = models.UUIDField()
	  author = GenericForeignKey(
	      "author_content_type",
	      "author_object_id"
	  )

		class Meta:
        indexes = [
            models.Index(fields=["author_content_type", "author_object_id"]),
        ]
β€£

DRF ModelViewSet Create with Generic Field

from django.contrib.contenttypes.models import ContentType
from rest_framework import viewset
from rest_framework.permissions import IsAuthenticated

from .models import Message
from .serializers import MessageSerializer

class MessageViewSet(viewsets.ModelViewSet):
    model = Message
    serializer_class = MessageSerializer
		permission_classes = [IsAuthenticated]

    def create(self, request, *args, **kwargs):
				author = request.user
        request.data['author_content_type'] = ContentType.objects.get_for_model(author).id
        request.data['author_object_id'] = request.user.id

        return super().create(request, *args, **kwargs)

Related Posts

Knowledge Base: Django Generic Fields
Guidelines and Answers to all things Django Generic Fields
Nov 14, 2023 7:33 AM
Custom Django Admin Add Template
How to: customize Django Admin model templates
Nov 14, 2023 7:29 AM
Custom Django Unfold Admin Dashboard
Setup a custom admin dashboard in an existing repo, exactly like the one shown on Unfold Formula Demo project.
Nov 14, 2023 7:29 AM
πŸ”’
Django x React Native Authentication
Implementing Google and Microsoft Azure Active Directory OAuth in Django Rest Framework and React Native Expo
Nov 14, 2023 7:28 AM

πŸ¦„βš‘