Django3.1です。
ポリモーフィック関連を表現したい場合、GenericForeignKey
, GenericRelation
, ContentType
を使う
モデル定義
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelaton
from django.contrib.contenttypes.models import ContentType
from django.db import models
class Attachment(models.Model):
``` 添付ファイル ```
src = models.FileField(null=False)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.IntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
class Entry(models.Model):
``` エントリ ```
title = models.CharField(max_length=255)
body = models.TextField()
attachments = GenericRelation(Attachment)
class Comment(models.Model):
``` エントリに対するコメント ```
body = models.TextField()
attachments = GenericRelation(Attachment)
参照
entry = Entry.objects.first()
# create
entry.attachments.create(src=file_obj)
# load
entry.attachments.first().src.file.read()
comment = Comment.objects.first()
# create
comment.attachments.create(src=file_obj)
# load
comments.attachments.first().src.file.read()