具有两个可能模型之一的外键的django模型 [英] django model with foreign key to one of two possible models

查看:67
本文介绍了具有两个可能模型之一的外键的django模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个相似但不完全相同的模型。这是我能想到的最好的抽象概念。

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(?????????)

我的问题在于,取决于isCat的值,Pet模型的动物领域将成为Cat或Dog模型的外键。我该怎么做?

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.

推荐答案

您应该看到通用关系

这篇关于具有两个可能模型之一的外键的django模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆