Reputation: 4008
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
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
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 ForeignKey
s 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