0

I have a Django app where I want to use a set of abstract base classes to define certain models. I want to connect some of these abstract models through foreign keys.

I know that Django does not allow models.ForeignKey to abstract models. I've done some searching on StackOverflow and the general consensus solution seems to be - using GenericForeignKey. However, from my understanding, this results in an extra db-level SELECT call. I want to avoid this because quite a few of my abstract models have this kind of relationship. An example is given below:

class Person (models.Model):
    name = models.CharField (max_length=256)

    class Meta:
        abstract = True


class Phone (models.Model):
    phone_no = models.BigIntegerField ()
    owner = models.ForeignKey (Person) # This is, of course, wrong. I'd like something like this.

    class Meta:
        abstract = True

Besides the posts about GenericForeignKey, I also came across a post about dynamic model generation. The link is given below. The question-poster themselves have provided the answer.

Defining an Abstract model with a ForeignKey to another Abstract model

I would like to ask:

  1. if this still holds for the current versions of Django,
  2. if there are any caveats I should be aware of, and
  3. if there is perhaps a more contemporary solution?

Thank you.

  • Why do you make `Person` abstract? Referring to an abstract class is a bit "non-sensical", since there is no real table to target. – Willem Van Onsem Jan 19 '20 at 10:13
  • 1
    having a foreign key relation between two abstract model is illogical. Abstract model exist for the very purpose of inheritance. Concrete models must inherit abstract model. There is no table in database for abstract models. I think you should look for alternative solution. – Mohit Rustagi Jan 19 '20 at 10:24

1 Answers1

0

I have solved the issue. As pointed by Willem and Mohit, I was thinking about the problem wrongly (I come from the Cpp world and am very new to the Python/Django programming mindset).

I ended up having the abstract classes defined without any relationships and then having concrete classes derived from these abstract ones actually define the relationships. This is also in keeping with the DRY principle.