我根据请求在数据库中动态存储信息:
// 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'])
问题是 request.POST['value'] 有时包含外部记录的主键(即整数),而 Django 期望列的值是 ForeignModel 类型的对象:
Cannot assign "u'122'": "ModelA.b" must be a "ModelB" instance.
现在,有没有一种优雅的方法来动态检查 b 是否是包含外键的列以及这些键链接到什么模型? (这样我就可以通过它的主键加载外部记录并将其分配给 ModelA?)或者 Django 不向程序员提供这样的信息所以我真的不得不弄脏我的手并在外部使用 isinstance() -关键列?
最佳答案
您可以在模型 _meta 对象上使用 get_field_by_name:
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
假设你有一个模型类 MyModel 你会这样使用它:
fk_model = get_fk_model(MyModel, 'fieldname')
关于python - 如何找出模型的列是否为外键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2608067/