When should we use Generic relation or ManytoMany relation?
Standard foreign key
class Object1(models.Model):
...
class Object1Task(models.Model):
object1 = models.ForeignKey(Object1)
...
class Object20(models.Model):
...
class Object20Task(models.Model):
object20 = models.ForeignKey(Object20)
If you have many class (Object1
to Object20
) that have similar table (Object1Task
to Object20Task
) that contains exact fields. It’s not DRY.
Generic relation
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
class Task(models.Model):
content_type = models.ForeignKey(
ContentType,
null=True,
on_delete=models.SET_NULL,
related_name="task",
)
object_id = models.PositiveBigIntegerField(
blank=True,
null=True,
)
content_object = GenericForeignKey(
"content_type",
"object_id",
)
...
By using Generic relation, we don’t need to create Object1Task
to Object20Task
, just Task
table is fine. It is DRY and create fewer database tables than foreign key & manytomany approach, but the issue is that querying is not easy, we need to use GenericRelation
.
ManytoMany
class Task(models.Model):
object1 = models.ManyToManyField(object1)
...
object20 = models.ManyToManyField(object20)
If we use ManyToManyField
, it’s DRY and easier to query than generic relation.