aslheyrr
aslheyrr

Reputation: 372

ForeignKey relation to abstract class

I'm tring some like this:

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

class C1(F):
class C2(F):

class D(F):
        pid = models.ForeignKey(Cx)

where Cx could be either C1 or C2, but I don't know how do it.

could anybody lead me? Thanks

Python 3.3 Django 1.7

Upvotes: 6

Views: 1769

Answers (3)

ChrisRob
ChrisRob

Reputation: 1552

I solved my problem with another abstract class. Like this:

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

class D(F):
    class Meta:
         abstract = True

class C1(F):
class C2(F):

class D1(D):
    pid = models.ForeignKey(C1)
class D2(D):
    pid = models.ForeignKey(C2)

Upvotes: 0

WhyNotHugo
WhyNotHugo

Reputation: 9924

As mentioned in the other reply, since abstract classes have no table, you can't relate to them.

You can, however, imitate this behaviour with one-to-one relationships:

class F(models.Model):
    pass # stuff here

class C1(models.Model):
    f = models.OneToOneField(F)

class C2(models.Model):
    f = models.OneToOneField(F)

class D(F):
        pid = models.ForeignKeyField(F)

You'll have to manually find if pid is C1 or C2, but you'll never have a scenario where a single instance of F is related to more than one instance of either C1 or C2.

Upvotes: 1

user764357
user764357

Reputation:

What you are asking isn't possible directly, you can't have a ForeignKey to an abstract model, as abstract models don't have database tables to link to.

You can do either of two things. Either make F a concrete class, there are some downsides to this, but its not a bad way to go.

class F(models.Model):
    pass

class C1(F):
    pass
class C2(F):
    pass

class D(F):
        pid = models.ForeignKey(F)

Or use a GenericforeignKey which is a bit more complicated, especially if you need to limit the choices of model.

Upvotes: 2

Related Questions