views:

47

answers:

2

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?

A: 

Explore the "ModelChoiceField" fields. Can they solve your problem putting foreign keys into forms for you; rather than doing that yourself.

http://docs.djangoproject.com/en/1.1/ref/forms/fields/#fields-which-handle-relationships

record = forms.ModelChoiceField(queryset=table_obj.objects.all())
John Mee
Thanks, I would do that if I didn't have special requirements: All my "forms" are JS-powered inline-edit forms. That makes it quite a challenge to generate them with Django's API, one which I'm rather not willing to take.
codethief
+1  A: 

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')

John Montgomery