I would like to define a Django Model looking like this:
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
class Foo(models.Model):
object_id_1 = models.UUIDField()
content_type_1 = models.ForeignKey(ContentType)
object_id_2 = models.UUIDField()
content_type_3 = models.ForeignKey(ContentType)
object_id_3 = models.UUIDField()
content_type_3 = models.ForeignKey(ContentType)
# etc.
d1 = GenericForeignKey("content_type_1", "object_id_1")
d2 = GenericForeignKey("content_type_2", "object_id_2")
d3 = GenericForeignKey("content_type_3", "object_id_3")
# etc.
Obviously, the more dimensions (d
stands for "dimension") I add, the messier it gets: this isn't very DRY, all the more since I've removed the many fields options in this example.
Is there a way to dynamically define these model attributes, for instance in a for
loop, without using eval
? If not, what would be the cleanest and safest way to resort to eval
here?
I've found a very similar Stackoverflow question here but it is more specific and it hasn't got any generic answer.