BATMAN
BATMAN

Reputation: 373

Foreign Key column with keys from different models

Lets say I have 4 models, A, B, C, X

A contains A1,A2,...An (similarly B and C)

I have an object in X, say X1 which is related to an object from category either A, B or C.

I have a column in X's model as category.

How can I relate it to different models of A, B and C?

If this cannot be done with a single column, what is the best way to implement this?

Sorry for asking a basic question.

Thanks in advance :)

Upvotes: 1

Views: 50

Answers (1)

GwynBleidD
GwynBleidD

Reputation: 20539

You have 2 options for that

  1. use model (let's name it Base), that will be the parent model for A, B and C:

    class Base(models.Model):
        # you can put any fields here that are common to A, B and C, but not having any fields here is fine
        pass
    
    class A(Base):
        # fields for A, models B and C will be similar so I'm skipping them
        pass
    

    Now you can create foreign key to Base in your X model and extract specialized model in next step. To simplify extraction of specialized model, you can use django-polymorphic

  2. Use generic relation:

    class X(models.Model):
        content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
        object_id = models.PositiveIntegerField()
        content_object = GenericForeignKey('content_type', 'object_id')
    

    This approach is more universal, but also doesn't give you as much control over what is actually being referenced in model X. It doesn't also play well with custom primary keys. There are also no constraints on database side that will keep foreign keys valid.

Upvotes: 1

Related Questions