Django: set the 'through' argument for ManyToMany field in the extended class

220 views Asked by At

I want to extend an abstract model class with a ManyToMany field and set the field's through argument to refer to my own model/table. I tried the following, inspired by this: How to override the default value of a Model Field from an Abstract Base Class

# first_app    
class A(models.Model):

    name = models.CharField(max_length=200)


class B(models.Model):
    a = models.ManyToManyField(A)

    class Meta:
        abstract = True

# myapp: my extended and through models
class C(B):
    pass
C._meta.get_field('a').through = 'D'

class D(models.Model):
    a = models.ForeignKey(A)
    c = models.ForeignKey(C)
    default_rel = models.BooleanField(default=False)

The problem is Django creates both myapp_c_a and myapp_d tables, and uses myapp_c_a instead of myapp_d, which means it ignores the through argument.

So, my question is how I can override the ManyToMany field in C so it uses D.

0

There are 0 answers