Django Model将外键设为另一个模型的一个字段 [英] Django Model set foreign key to a field of another Model
问题描述
有没有办法在django中设置一个外键到另外一个模型的字段?
Is there any way to set a foreign key in django to a field of another model?
例如,假设我有一个ValidationRule对象。我想要规则定义另一个模型中要被验证的字段(以及一些其他信息,例如它是否可以为空,数据类型,范围等)。
For example, imagine I have a ValidationRule object. And I want the rule to define what field in another model is to be validated (as well as some other information, such as whether it can be null, a data-type, range, etc.)
有没有办法在django中存储这个字段级映射?
Is there a way to store this field-level mapping in django?
推荐答案
是和否。 FK关系在类级别进行描述,并反映数据库中的FK关联,因此您无法直接在FK参数中添加额外的信息。
Yes and no. The FK relationship is described at the class level, and mirrors the FK association in the database, so you can't add extra information directly in the FK parameter.
我建议有一个字符串在另一个表上保存字段名称:
Instead, I'd recommend having a string that holds the field name on the other table:
class ValidationRule(models.Model):
other = models.ForeignKey(OtherModel)
other_field = models.CharField(max_length=256)
这样,您可以通过以下方式获取该字段:
This way, you can obtain the field with:
v = ValidationRule.objects.get(id=1)
field = getattr(v, v.other_field)
请注意,如果您使用多对多字段(而不是一对多),内置支持创建自定义中间表以使用 through 选项。
Note that if you're using Many-to-Many fields (rather than a One-to-Many), there's built-in support for creating custom intermediary tables to hold meta data with the through option.
这篇关于Django Model将外键设为另一个模型的一个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!