Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out whether a model's column is a foreign key?

I'm dynamically storing information in the database depending on the request:

// table, id and column are provided by the request
table_obj = getattr(models, table)
record = table_obj.objects.get(pk=id)

setattr(record, column, request.POST['value'])

The problem is that request.POST['value'] sometimes contains a foreign record's primary key (i.e. an integer) whereas Django expects the column's value to be an object of type ForeignModel:

Cannot assign "u'122'": "ModelA.b" must be a "ModelB" instance.

Now, is there an elegant way to dynamically check whether b is a column containing foreign keys and what model these keys are linked to? (So that I can load the foreign record by it's primary key and assign it to ModelA?) Or doesn't Django provide information like this to the programmer so I really have to get my hands dirty and use isinstance() on the foreign-key column?

like image 845
balu Avatar asked Apr 09 '10 14:04

balu


People also ask

What is foreign key example?

In simpler words, a foreign key is a set of attributes that references a candidate key. For example, a table called TEAM may have an attribute, MEMBER_NAME, which is a foreign key referencing a candidate key, PERSON_NAME, in the PERSON table.

What is a foreign key in a table?

A foreign key is a column or a set of columns in a table whose values correspond to the values of the primary key in another table. In order to add a row with a given foreign key value, there must exist a row in the related table with the same primary key value.

Do all tables need a foreign key?

Note that foreign keys are not mandatory, and a table may have no foreign keys. Conversely, every column in a table may have a foreign key constraint.

What is foreign key in Django model?

What is ForeignKey in Django? ForeignKey is a Field (which represents a column in a database table), and it's used to create many-to-one relationships within tables. It's a standard practice in relational databases to connect data using ForeignKeys.


1 Answers

You can use get_field_by_name on the models _meta object:


from django.db.models import ForeignKey

def get_fk_model(model, fieldname):
    """Returns None if not foreignkey, otherswise the relevant model"""
    field_object, model, direct, m2m = model._meta.get_field_by_name(fieldname)
    if not m2m and direct and isinstance(field_object, ForeignKey):
        return field_object.rel.to
    return None

Assuming you had a model class MyModel you would use this thus:


fk_model = get_fk_model(MyModel, 'fieldname')

like image 174
John Montgomery Avatar answered Oct 29 '22 00:10

John Montgomery