Search code examples
pythondjangodjango-modelsdjango-polymorphic

Through relationship using Django polymorphic model


I'm trying to use a through relationship between a polymorphic and a non-polymorphic table with the the RankedAthlete model:

class ChoiceBlank(PolymorphicModel):
    pass

class ChoiceAthlete(ChoiceBlank):
    choice = models.ForeignKey('SomeModel', on_delete=models.CASCADE)

class BetMultiple(models.Model):
    answer = models.ManyToManyField('ChoiceBlank', blank=True, through='RankedAthlete')

class RankedAthlete(models.Model):
    choiceAthlete = models.ForeignKey('ChoiceBlank', on_delete=models.CASCADE)
    bet = models.ForeignKey('BetMultiple', on_delete=models.CASCADE)
    rank = models.IntegerField()

This doesn't work because RankedAthlete expects a ChoiceBlank and a ValueError is raised when I create one. Conversely, I can't migrate my db if I replace choice with a ChoiceAthlete.

Django-polymorphic doc doesn't mention my use case, is it unsupported? Is there a way to make this work?


Solution

  • This seems to not be possible. As an alternative, since I only need one type of using an ordered answer, I created a model specificaly for it using the child model rather than the parent model and changed RankedAthlete accordingly:

    class BetMultipleOrdered(models.Model):
        answer = models.ManyToManyField('ChoiceAthlete', blank=True, through='RankedAthlete')
    
    class RankedAthlete(models.Model):
        choiceAthlete = models.ForeignKey('ChoiceAthlete', on_delete=models.CASCADE)
        bet = models.ForeignKey('BetMultiple', on_delete=models.CASCADE)
        rank = models.IntegerField()
    

    Another alternative would be to use ContentType.