[Django]-Django: Model Inheritance: FK & M2M

1👍

I figured out the problem…..

This will work:

from django.db import models

class CommonInfo(models.Model):

    name = models.CharField(max_length=100)

class Base(models.Model):
    m2m = models.ForeignKey(CommonInfo, related_name="%(app_label)s_%(class)s_related")

    class Meta:
        abstract = True

class ChildA(Base):
    pass

This will give you the error: AssertionError: ForeignKey cannot define a relation with abstract class OtherModel.This is because you can’t have a FK relationship or M2M relationship on an abstract pointing to ANOTHER abstract class.

from django.db import models

class CommonInfo(models.Model):
    class Meta:
        abstract = True

    name = models.CharField(max_length=100)

class Base(models.Model):
    m2m = models.ForeignKey(CommonInfo, related_name="%(app_label)s_%(class)s_related")

    class Meta:
        abstract = True

class ChildA(Base):
    pass

This is sad news for me. Sad news indeed. I hope my sad news benefits someone else.

2👍

You cannot have a relation with an abstract model, but this is what you are trying to do (ManyToManyField to OtherModel). If you want to make this work you need to remove abstract = True from OtherModel and add common to your INSTALLED_APPS!

If you want to relate to different sublasses of OtherModel from the subclasses of Base you will need to define the relation on the subclass, not on the abstract model!

Leave a comment