Search code examples
pythondjangomodels

Dynamic relation between models in Django


I'm trying to make a dynamic relation between models but I'm just starting with Django. It's a simple task assignment apps. In this example I've 3 models :

class A(models.Model):
    name = models.CharField(_(u'Name'), max_length=255)

class B(models.Model):
    name = models.CharField(_(u'Name'), max_length=255)

class Task (models.Model):
    parent_A = models.ForeignKey(A, verbose_name=_(u'Parent A'), null=True, blank=True, related_name = "%(app_label)s_%(class)s_parent_A")
    parent_B = models.ForeignKey(B, verbose_name=_(u'Parent B'), null=True, blank=True, related_name = "%(app_label)s_%(class)s_parent_B")

but now the problem is, if I want 5 models to be able to be parent of Task, I will need to implement 5 foreign key fields ... There is a way in Django to set up something like that ? Cheers


Solution

  • Generic relations are what you want.