Search code examples
pythonpython-3.xdjangodjango-modelsforeign-keys

In Django, is there any way to set a foreign key to a field of another model?


In Django, is there any way to set a foreign key 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?


Solution

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