meshy
meshy

Reputation: 9076

How can I get the name of a ForeignKey relation from one model to another in django?

Assuming we know a ForeignKey field exists on one known arbitrary model that references another, how do we find the name of this relationship?

I am looking for something like:

Spam.field_relating_to(Egg)

that would return u'egg' where Spam looks something like this:

from django.db import models

class Spam(models.Model)
    egg = models.ForeignKey(Egg)

Is this possible?

Upvotes: 2

Views: 110

Answers (2)

Jordan Reiter
Jordan Reiter

Reputation: 21002

To follow up on Max Peterson's answer, here is code you could use:

class RelationshipMixin(object):
    def field_relating_to(other):
        for field in self._meta.fields:
            if hasattr(field, 'rel') and field.rel.to == other:
                return field.name
        return None

class Spam(models.Model, RelationshipMixin):
    egg = models.ForeignKey(Egg)

and then

>>> Spam.field_relating_to(Egg)

should work.

Note that this might match one-to-one and many-to-many relationships as well, so if that's important to check for you'll have to change the code somewhat.

Haven't tested it, so double check.

Upvotes: 2

Max Peterson
Max Peterson

Reputation: 673

Find the first field in Spam._meta.fields that has a rel.to Egg

Upvotes: 4

Related Questions