user3541631
user3541631

Reputation: 4008

Getting a Model Foreign Key name and value?

I have the following model:

class Item(models.Model):
    owner = models.ForeignKey(Owner, on_delete=models.CASCADE)

I want to write a general function/utility to get the Foreign Key name and value passed it to another function as argument:

In the code below I get the FK

for field in self._meta.get_fields(include_parents=False):
            if isinstance(field, models.ForeignKey):
...........

function f2 ({fk_name:value, fk_name2:value})

How do I get the name(owner) and the value (owner_id) ?

Upvotes: 2

Views: 1605

Answers (2)

The Hog
The Hog

Reputation: 969

for field in self._meta.get_fields(include_parents=False):
    if isinstance(field, models.ForeignKey):
        print(field.name, getattr(self, field.name, None))

this works

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477883

A ForeignKey object has an attribute, attname, that specifies the name of the attribute holding the value of the primary key it refers to.

For your owner, the value of field.attname will here be owner_id, if you do not change anything.

We can define a dictionary that maps the names of ForeignKeys to the attributes that store the primary key like:

{
    field.name: field.attname
    for field in self._meta.get_fields(include_parents=False)
    if isinstance(field, models.ForeignKey)
}

For your model, this thus will generate a dictionary:

{'owner': 'owner_id'}

Upvotes: 2

Related Questions