Django Model set foreign key to a field of another Model

会有一股神秘感。 提交于 2019-12-30 01:41:06

问题


Is there any way to set a foreign key in django to a field of another model?

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.)

Is there a way to store this field-level mapping in django?


回答1:


I haven't tried this, but it seems that since Django 1.0 you can do something like:

class Foo(models.Model):
    foo = models.ForeignKey(Bar, to_field='bar')

Documentation for this is here.




回答2:


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)

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.



来源:https://stackoverflow.com/questions/730207/django-model-set-foreign-key-to-a-field-of-another-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!