在我看来,我试图删除/删除一些以real_
开头的字段。不过,我想一定是一种以编程方式做到这一点访问以特定字符串开头的实例属性
plan = get_object_or_404(Plan, pk=self.kwargs['plan_id'])
plan.real_time = None
plan.real_date = None
plan.real_comments = None
plan.real_whatever = None
....
plan.save()
:
我可以这样做。我所需要做的就是访问这些字段的名称,比较它是否确实以real_
开头,然后更新该字段。
我正在使用get_fields()
(as per the documentation)。虽然我不确定如何做最后一部分。
以下是我认为的代码:
plan = get_object_or_404(Plan, pk=self.kwargs['plan_id'])
plan_fields = plan._meta.get_fields()
for field in plan_fields:
if field.name[:5] == "real_":
plan.<not sure what to do here> = None
plan.save()
我想我一定是忽视的东西少。任何指针?
使用Django 1.9。
看看内置的getattr()函数是否能够满足您的需求。 – theWanderer4865