本文介绍了具有多种类型的Django Model域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下(简化)模型:

I have the following (simplified) models:

class Structure(models.Model):
name=models.CharField(max_length=100, unique=True)

class Unit(models.Model):
name=models.CharField(max_length=100, unique=True)



Each model, also has a builtFrom field, which shows what the item is built from, for example:

class Unit(models.Model):
name=models.CharField(max_length=100, unique=True)
builtFrom=models.ForeignKey(Structure)

然而,builtFrom可以从单元类型或一个结构类型。有没有一个简单的方法来代表我的模型?

However, builtFrom can be populated from either a Unit type, or a Structure type. Is there an easy way to represent this in my models?

我唯一可以想到的是有一个单独的模型,像这样:

The only thing I can think of is to have a separate model, like so:

class BuiltFromItem(models.Model):
structure=models.ForeignKey(Structure)
unit=models.ForeignKey(Structure)


class Unit(models.Model):
name=models.CharField(max_length=100, unique=True)
builtFrom=models.ForeignKey(BuiltFromItem)

然后有一个BuiltFromItem字段为null。然后,当我需要数据时,弄清楚它是由其构建的结构或单元。有没有更好的解决方案?

And then have one of the BuiltFromItem fields just be null. Then, when I need the data, figure out whether it is a structure or unit that it is built from. Is there a better solution for this?

推荐答案

你想要Django文件被称为。 Django内置了对它们的支持。

You want what the Django docs refer to as a "generic relation". Support for them is built into Django.

这篇关于具有多种类型的Django Model域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-27 08:11