python - 如何找出模型的列是否为外键?

标签 python django foreign-keys

我根据请求在数据库中动态存储信息:

// 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/

相关文章:

python - 如何使用不同的 View 进行 django 注册?

c# - EntityFramework : 1:0. .1 关系反序列化为集合

python - 在发送查看之前修改 web2py 中的 CRUD 表单

python - 如何根据另一个数据框的条件创建新的数据框

python - 在单独的线程中(并行)将数据写入光盘

python - Django Rest Framework 自定义响应消息

python - 有人在 django 中尝试过 html2pdf 吗?

python - Python程序的初始化

python - 名称错误 : name 'BillPayer' is not defined

android - 房间 : deleting a ForeignKey or setting the ForeignKey to a default value