How To…
Create a Generic Field
from django.db import modelsfrom django.contrib.contenttypes.fields import GenericForeignKeyfrom 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 modelsfrom django.contrib.contenttypes.fields import GenericForeignKeyfrom 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 ContentTypefrom rest_framework import viewsetfrom rest_framework.permissions import IsAuthenticated
from .models import Messagefrom .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)