django model with foreign key to one of two possib

2020-04-11 13:00发布

I have a two models that are similar, but not exactly the same. Here's the best abstraction of the problem that I can come up with.

class Cat(models.Model):
    name = models.TextField()
    breed = models.TextField()

class Dog(models.Model):
    name = models.TextField()
    color = models.TextField()

And now I need to make another model like this.

class Pet(models.Model):
    favoriteFood = models.TextField()
    isCat = models.BooleanField()
    animal = models.ForeignKey(?????????)

My problem is that the animal field of the Pet model is going to be a foreign key to either the Cat or the Dog model depending on the value of isCat. How can I do that?

Now, I know this is an unusual/awkward schema in the first place, but I wasn't involved in its creation and I can't change it. I just have to support it. I'm writing these models for an existing database.

3条回答
倾城 Initia
2楼-- · 2020-04-11 13:08

Generic relations is a direct answer.

查看更多
我命由我不由天
3楼-- · 2020-04-11 13:14

You should see Generic relations.

查看更多
神经病院院长
4楼-- · 2020-04-11 13:26

Another option for this use case is: django-polymorphic :)

查看更多
登录 后发表回答