简体   繁体   English

设计具有“专有”外键关系的Django模型的建议

[英]Advice on designing django model with “exclusive” foreign key relationships

I want to design a Task model that can be associated to Project Models, another X model, and other Task models. 我想设计一个可以与项目模型,另一个X模型和其他Task模型关联的Task模型。 The obvious choice is a foreign key, but I want any particular instance of that Task model to only be associated to only one of those model types, that is, if a Task model has a relationship with a Project model, it cannot have a relationship with another Task model, and so on. 显而易见的选择是外键,但是我希望该Task模型的任何特定实例仅与那些模型类型中的一种相关联,也就是说,如果Task模型与Project模型有关系,则不能有关系。与另一个任务模型,依此类推。 Any advice in what would be the best way to represent this? 有什么建议可以代表最好的方式吗? Thanks. 谢谢。

Have a look at Generic relation . 看一下通用关系 It lets you define a foreign key on multiple models. 它使您可以在多个模型上定义外键。 This way your task is only linked to one of your models. 这样,您的任务仅链接到您的模型之一。

What I have done is to inherit from a base class on all my models that will be related to tasks. 我要做的是从与任务相关的所有模型的基类继承。 Task models points to that base class on the ForeignKey with unique=True, and it seems like all subclasses inherit the relationship. 任务模型指向ForeignKey上具有unique = True的基类,并且似乎所有子类都继承了该关系。 Thanks. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM