2

The simplest case of creating a generic foreign key is like this:

class ModelWithGFK(models.Model):
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

But in my case there are other fields which I can infer the content type from, so adding a content_type FK is both redundant and prone to cause inconsistency over time. So I tried this:

class ModelWithGFK(models.
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

    @property
    def content_type(self):
        # Figure out which content type this instance should have FK to
        return ContentType.objects.get(..........)

but seems like GFK class only accepts the content type argument to be a foreign key:

def _check_content_type_field(self):
    """
    Check if field named `field_name` in model `model` exists and is a
    valid content_type field (is a ForeignKey to ContentType).
    """

Is there a workaround (perhaps via overriding GFK and some of its methods like get_content_type) or I shall give in, add the FK and live in a constant fear of inconsistency and agony of knowing about this (tiny) inevitable redundancy?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Mohammad Jafar Mashhadi
  • 4,102
  • 3
  • 29
  • 49

0 Answers0