[Django]-Django – What are the alternatives to having a ForeignKey to an abstract class?

3πŸ‘

βœ…

The reason the ForeignKey cannot reference an abstract model directly is that individual models that inherit from the abstract model actually have their own tables in the database.

Foreign keys are simply integers referencing the id from the related table, so ambiguity would be created if a foreign key was related to an abstract model. For example there might be be a Buyer and Seller instance each with an id of 1, and the manager would not know which one to load.

Using a generic relation solves this problem by also remembering which model you are talking about in the relationship.

It does not require any additional models, it simply uses one extra column.

Example –

from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey

class Foo(models.Model):
  company_type = models.ForeignKey(ContentType)
  company_id = models.PositiveIntegerField()
  company = GenericForeignKey('company_type', 'company_id')

And then –

>>> seller = Seller.objects.create()
>>> buyer = Buyer.objects.create()
>>> 
>>> foo1 = Foo.objects.create(company = seller) 
>>> foo2 = Foo.objects.create(company = buyer) 
>>> 
>>> foo1.company 
<Seller: Seller object>
>>> foo2.company 
<Buyer: Buyer object>
πŸ‘€metahamza

Leave a comment