Question

I want to accomplish the following: I have three classes derived from an abstract class:

class Person(models.Model):
  name = models.CharField()
  ...
  class Meta:
    abstract = True

class TypA(Person):
  ...

class TypB(Person):
  ...

class TypC(Person):
  ...

In another class I would like to reference TypA and TypB as a Foreign Key, something like this:

class Project(models.Model):
  worker = models.ForeignKey(TypA or TypB)

Since it is not possible to declare two different models as a Foreign Key I am on the look for solutions. I read about Generic Foreign Keys; but I am unsure how to apply that to my model.

Another idea is to use the limit_choices_to declaration for ForeignKeys.

worker = models.ForeignKey(Person, limit_choices_to={??})

But this is not possible as it seems:

Field defines a relation with model 'Person', which is either not installed, or is abstract.

Thank you in advance for the help.

Was it helpful?

Solution

A Django ForeignKey field translates to a database foreign key. Your Person model is abstract, so that one doesn't exist in the database, so there can be no foreign keys to that one.

Likewise a database foreign key can only reference one table, not two.

If you really want a flexible relation to more than one kind of table, the only possibility I see is Django's contenttypes framework.

You also want to limit the kinds of models you can point at. For that you'd best look at How can I restrict Django's GenericForeignKey to a list of models? for an example.

OTHER TIPS

you just need to reference your abstract class(like JAVA):

class Project(models.Model):
    worker = models.ForeignKey(Person)


#in your code:
worker = TypeA()
worker.save()
proj = Project()
proj.worker = worker
proj.save()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top